对象没有't支撑方法
Object doesn't support method
我正试图运行以下代码,但在gameRoop函数中收到一个错误:JavaScript运行时错误:对象不支持属性或方法"update"。
我是一名初学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);
}
在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);
}
在具有ES5功能的JavaScript引擎上(或者如果您使用的是ES5"填充程序"),您可以将Core
更改为:
function Core(context) {
this.context = context;
this.fps = 500;
this.sprite = new Sprite();
this.boundGameLoop = this.gameLoop.bind(this);
}
更多阅读:
- 神话般的方法
- 你必须记住
this
- ES5规范中的函数#bind
附带说明:您的代码依赖于"自动分号插入"这一恐怖功能。(您的所有职能分配(Core.prototype.run = function() { ... }
)在结束的}
之后都需要分号。)
您需要的是.bind.
setInterval(this.gameLoop.bind(this), this.fps)
尝试重新整理代码,以便在调用之前声明更新,例如
Core.prototype.update = function () {
this.sprite.x += 50;
this.sprite.y += 50;
}
Core.prototype.gameLoop = function () {
this.update();
this.draw();
}
相关文章:
- 序列化数据属性中对象的最可靠方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 如何从对象的原型方法访问JavaScript对象属性
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- 设置嵌套对象属性的更好方法
- JQuery示例不起作用-“;对象没有't支持属性或方法'按钮'&”;
- 对象不支持属性或方法“自动完成”
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- 对象文字方法上的Javascript绑定不起作用
- Meteor应用程序无法运行-对象#<编译器>没有方法'主机'
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- Underscore.js某些对象的所有方法的总和
- 对象#<XMLHttpRequest>没有方法'完成'
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 丢失对象“;这个“;方法中的上下文
- 如何在ajax中调用javascript对象的方法
- 为什么页面方法对象未定义
- 如何使用在另一个文件中定义的JavaScript方法/对象
- 如何告诉JsHint忽略“未解析的函数或方法”?对象上的警告
- 使用jinja/javascript动态创建方法/对象