2012-03-25 128 views
0

我试图运行下面的代码,但在gameLoop函数中出现错误:JavaScript运行时错误:对象不支持属性或方法'更新'。对象不支持方法

我是一个开始的JavaScript程序员。你能发现这个代码有什么问题吗?

function Core(context) { 
    this.context = context; 
    this.fps = 500; 
    this.sprite = new Sprite(); 
} 

Core.prototype.run = function() { 
    setInterval(this.gameLoop, this.fps); // <<<< PROBLEM 
} 

Core.prototype.gameLoop = function() { 
    this.update(); 
    this.draw(); 
} 

Core.prototype.update = function() { 
    this.sprite.x += 50; 
    this.sprite.y += 50; 
} 

Core.prototype.draw = function() { 
    this.context.clearRect(0, 0, 300, 300); 
    this.context.fillRect(this.sprite.x, this.sprite.y, 50, 50); 
    this.context.fillText('x: ' + this.sprite.x + ' y: ' + this.sprite.y, 10, 250); 
} 
+0

固定码:http://pastebin.com/xuNTQSrP - 'this'在'Core.prototype.gameLoop'没有解决的。预期的,因为'setInterval'。 – 2012-03-25 11:03:06

+0

@Milosz:没有必要,只有当'gameLoop'被**调用**时才会被定义,而不是定义它时。 – 2012-03-25 11:03:19

回答

1

在JavaScript中,this由函数如何被调用完全定义的,而不是在那里,或者它如何定义的。问题是setInterval不会使用正确的this值调用您的代码。要解决:

function Core(context) { 
    var self = this; 

    this.context = context; 
    this.fps = 500; 
    this.sprite = new Sprite(); 
    this.boundGameLoop = function() { 
     self.gameLoop(); 
    }; 
} 

Core.prototype.run = function() { 
    setInterval(this.boundGameLoop, this.fps); 
} 

在JavaScript引擎具有ES5功能(或者,如果您使用的是ES5 “垫片”),你可以改变Core到:

function Core(context) { 
    this.context = context; 
    this.fps = 500; 
    this.sprite = new Sprite(); 
    this.boundGameLoop = this.gameLoop.bind(this); 
} 

更多阅读:


边注:您的代码依赖于为Automatic Semicolon Insertion恐怖。 (您的所有功能的作业  — Core.prototype.run = function() { ... })需要分号收盘}后)

+0

谢谢,这似乎运作良好。 – Aetherix 2012-03-25 11:11:04

+1

谢谢你的注意事项。我真的可以使用这些! :) – Aetherix 2012-03-25 11:17:42

+0

@Aetherix:很高兴帮助! – 2012-03-25 12:09:33

0

你需要的是.bind

setInterval(this.gameLoop.bind(this), this.fps) 
+0

谢谢,这确实有效。 – Aetherix 2012-03-25 11:11:17

+0

@Aetherix很高兴帮助:) – xdazz 2012-03-25 11:13:16

-1

尝试重新洗牌的代码,以便您声明更新你怎么称呼它,例如前

Core.prototype.update = function() { 
    this.sprite.x += 50; 
    this.sprite.y += 50; 
} 

Core.prototype.gameLoop = function() { 
    this.update(); 
    this.draw(); 
} 
相关问题