使用Object.call访问父作用域

时间:2015-05-04 16:13:55

标签: javascript

我想在onload函数中访问img属性我该怎么做?我将img属性添加到Picture对象并使用Picture对象的范围调用onload函数,但我无法访问this.img。

// picture
    function Picture(x, y, w, h, imgurl){
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.imgurl = imgurl;
        this.draw = drawPic;
        this.overcheck = overRect;
    } // end picture

    function drawPic(){
            this.img = new Image(); // add img to this scope
            this.img.src = this.imgurl;
            this.img.onload = function(){
                //ctx.drawImage(this.image, this.that.x, this.that.y, this.that.w, this.that.h);
                ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
            } // end onload
            this.img.onload.call(this);
    } // end drawPic

2 个答案:

答案 0 :(得分:1)

使用对this

的引用
function drawPic() {
  var self = this;
  this.img = new Image();
  this.img.src = this.imgurl;
  this.img.onload = function() {
    ctx.drawImage(self.img, self.x, self.y, self.w, self.h);
  };
}

答案 1 :(得分:0)

认为你必须在对象中定义函数:

function Picture(x, y, w, h, imgurl){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.imgurl = imgurl;
    this.draw = function(){
        this.img = new Image(); // add img to this scope
        this.img.src = this.imgurl;
        this.img.onload = function(){
            ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
        } // end onload
        this.img.onload.call(this);
    } // end drawPic;

    this.overcheck = overRect;
} // end picture