2

I have the charge method defined for MainCharacter class and inside it, another onload function for the image.

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);
    };
}

My problem is that this closure is not taking the object, and I am doing the next to solve the problem:

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);
    };
}

How I can solve this properly?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • You meant `this.canvas.drawImage(this.img, 0, 0, 55, 55, 12, 12, 80, 80);` in the first example? – thefourtheye Feb 28 '15 at 18:29
  • This seems to be a proper solution (except for the unnecessary `img` variable). What are you asking for? – Bergi Feb 28 '15 at 18:30
  • How is your question different from https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback? Please [edit] your post, if there's no difference I'll go close it as a duplicate – Bergi Feb 28 '15 at 18:31
  • yes, it does not take this.canvas. It says undefined. – Asier Devdream Feb 28 '15 at 18:32
  • Is 'this' set correctly when MainCharacter.charge is called? –  Feb 28 '15 at 18:35

1 Answers1

0

Have you considered using 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);
}
bvaughn
  • 13,300
  • 45
  • 46