javascript “this” keyword not referring to correct thing

瘦欲@ 提交于 2019-12-02 04:31:33

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.

seanmk

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!