javascript “this” keyword not referring to correct thing

前端 未结 3 1796
余生分开走
余生分开走 2021-01-23 12:05
var ball = {
    x: 20,
    y: 500,
    vx: 100,
    vy: 100,
    width: 13,
    height: 13,
    draw: function() { 
        var img = new Image();  
        img.src = \         


        
相关标签:
3条回答
  • 2021-01-23 12:31

    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);  
    
    0 讨论(0)
  • 2021-01-23 12: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.

    0 讨论(0)
  • 2021-01-23 12:36
    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

    0 讨论(0)
提交回复
热议问题