在JavaScript中关闭Object内部

时间:2015-02-28 18:27:29

标签: javascript

我为MainCharacter类定义了charge方法,在其中为图像设置了另一个onload函数。

var MainCharacter = function(canvas, X, Y) {
    this.canvas = canvas;

    this.X = (typeof X === "undefined") ? 10 : X;
    this.Y = (typeof Y === "undefined") ? 10 : Y;

    this.frameX = 0;
    this.frameY = 0;
    this.frameXWidth = this.frameX + 32;
    this.frameYHeight = this.frameY + 33;

    this.img = document.createElement('img');
    this.img.src = 'assets/img/maincharacter.png';
};

MainCharacter.prototype.charge = function() {
    this.img.onload = function() {
        self.canvas.drawImage(self.img, 0, 0, 55, 55, 12, 12, 80, 80);
    };
}

我的问题是这个闭包没有占用对象,我正在做下一个解决问题:

MainCharacter.prototype.charge = function () {
    var self = this;
    var img = this.img;
    img.onload = function () {
        self.canvas.drawImage(self.img, 0, 0, 55, 55, 12, 12, 80, 80);
    };
}

我如何正确解决这个问题?

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用Function.prototype.bind

MainCharacter.prototype.charge = function () {
    var img = this.img;
    img.onload = function () {
        this.canvas.drawImage(this.img, 0, 0, 55, 55, 12, 12, 80, 80);
    }.bind(this);
}