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.png';  
        img.onload = function(){  
            ctx.drawImage(img, this.x, this.y);  
        };
    },

I want the drawImage() line of code to refer to the ball.x and ball.y. Instead of using ball.x and ball.y, I want to use "this" keyword so that i can turn the ball object into a function that is a mass constructor/prototype if i end up wanting to (able to make ball1, ball2, ball3 etc.). I think "this" is not referring to ball anymore because it's in a nested function? Is there any way around that without hard-coding ball.x and ball.y into the drawImage arguments?

Answers:

Answer

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.

Answer

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);  
Answer
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 = new Image();  
       img.src = 'images/ball.png';  
       var balref = this;
       img.onload = function(){  
           ctx.drawImage(img, balref .x, balref.y);  
       }
}

var myball = new ball();
myball.draw();

Note: not tested

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.