javascript这个函数在一个函数中

javascript this function in a function

我正在尝试使用它。在创建对象的函数内部。但它似乎不起作用。

function enemy(x, y) {
        this.x = x;
        this.y = y;
        this.width = 32;
        this.height = 32;
        this.img = new Image();
        this.ready = false;
        this.img.onload = function() {
            this.ready = true;
        }
        this.img.src = "images/barney.png";
    }

this.ready 从未设置为 true,我需要这样才能渲染图像。有什么想法吗?

this 不再指向与第一个函数中相同的对象,请尝试分配 var self = this:

function enemy(x, y) {
        this.x = x;
        this.y = y;
        this.width = 32;
        this.height = 32;
        this.img = new Image();
        this.ready = false;
        var self = this; // note here how we save the value of `this`
        this.img.onload = function() {
            self.ready = true; // and use that saved `this` here
        }
        this.img.src = "images/barney.png";
    }

您需要这样做,因为当您在 onload 方法中时 this 的值会发生变化。

正如@JamesMcLaughlin 在下面指出的那样,如果您使用 ECMA6(Javascript Harmony),另一种解决方案是,如果您使用箭头函数语法,则可以为 this 保留相同的值:

function enemy(x, y) {
        this.x = x;
        this.y = y;
        this.width = 32;
        this.height = 32;
        this.img = new Image();
        this.ready = false;
        this.img.onload = () => this.ready = true;
        this.img.src = "images/barney.png";
    }

你应该接受另一个答案,但我会 post 这个答案以供将来参考。如果你的目标是 ES6,你可以使用粗箭头:

function enemy(x, y) {
    this.x = x;
    this.y = y;
    this.width = 32;
    this.height = 32;
    this.img = new Image();
    this.ready = false;
    this.img.onload = () => {
        this.ready = true;
    }
    this.img.src = "images/barney.png";
}