gpt4 book ai didi

javascript - 使用 Object.call 访问父作用域

转载 作者:行者123 更新时间:2023-12-03 10:12:44 26 4
gpt4 key购买 nike

我想在 onload 函数中访问 img 属性,我该怎么做?我向 Picture 对象添加了 img 属性,并在 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

最佳答案

使用对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);
};
}

关于javascript - 使用 Object.call 访问父作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com