对象没有't支撑方法

Object doesn't support method

本文关键字:方法 对象      更新时间:2023-09-26

我正试图运行以下代码,但在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();
}