下午好, 我正在玩一点 JavaScript,我有一个这种形式的“类”:
var Card = function(url,c){
...
this.img = new Image();
this.widthCurr = 0;
this.heightCurr = 0;
this.img.onload = this.imageLoaded()
this.img.src = this.url;
};
和一个定义为
的方法Card.prototype = {
imageLoaded : function(){
//my goal is to initialize this.widthCurr and this.heightCurr
console.log(this.img.width);
},
...
};
基本上我的目标是在加载 img 时用 img 的实际宽度和高度初始化 widthCurr 和 heightCurr 。我创建了新对象,并且 imageLoaded 中的 console.log 命令一直显示“0”,因此当时图像未加载。我尝试了一些修改,但似乎没有一个能起作用。我错过了什么重要的事情吗?我应该如何或在哪里设置这些值?
最佳答案
this.img.onload = this.imageLoaded()
您刚刚调用了该函数,并将其结果分配给 this.img.onload
。
相反,您需要分配函数本身,并且需要绑定(bind)this
:
this.img.onload = this.imageLoaded.bind(this)
关于 "class"内的 JavaScript Image 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692797/