Skip to content Skip to sidebar Skip to footer

Javascript "this" Keyword Not Referring To Correct Thing

var ball = { x: 20, y: 500, vx: 100, vy: 100, width: 13, height: 13, draw: function() { var img = new Image(); img.src = 'images/ball

Solution 1:

This is one of the tricky things about JavaScript: this is dynamic. To put it simply, the solution is to put the this you want in a variable while you have it and use that variable to refer to it:

var ball = {
    // ...draw: function() {
        // ...var myself = this;
        image.onload = function() {
            // use myself rather than this
        };
    }
};

Another solution is to fix the value of this. That is done using bind:

var ball = {
    // ...draw: function() {
        // ...
        image.onload = function() {
            // ...
        }.bind(this);
    }
};

That will bind the value of this inside the onload function to whatever it was when draw was called. This latter solution won't work on older browsers, but it is easily shimmed.

Solution 2:

Yes, basically you need to use a closure. All you need to do is refer to the variables by their parent instead of by the use of this, which will actually refer to the img element in the function. So just change your code to

ctx.drawImage(img, ball.x, ball.y);  

or even

ctx.drawImage(this, ball.x, ball.y);  

Solution 3:

var ball = function(){
    this.x= 20;
    this.y=500;
    this.vx= 100;
    this.vy= 100;
    this.width= 13;
    this.height= 13;
}

ball.prototype = {
    draw: function() { 
       var img = newImage();  
       img.src = 'images/ball.png';  
       var balref = this;
       img.onload = function(){  
           ctx.drawImage(img, balref .x, balref.y);  
       }
}

var myball = newball();
myball.draw();

Note: not tested

Post a Comment for "Javascript "this" Keyword Not Referring To Correct Thing"