javascript “this” keyword not referring to correct thing

一笑奈何 提交于 2019-12-04 05:14:42

问题


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?


回答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.




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



回答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 = 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



来源:https://stackoverflow.com/questions/17777341/javascript-this-keyword-not-referring-to-correct-thing

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