我正试图弄清楚为什么这不起作用,并想知道是否有人可以帮助我。基本上我需要这个对象的多个实例与不同的图像,我需要每个对象存储其相关图像的图像高度/宽度以进行进一步的操作,但onload事件永远不会触发?
如果您看到TestTheVar函数imgW从未设置为任何内容,那么请大家注意完整的代码。
<script type="text/javascript">
(function() {
var myTest = new TestObj();
mytest.TestTheVar();
})();
function TestObj() {
this.img = new Image();
this.img.onload = function(){
this.imgW = this.img.width;
this.imgH = this.img.height;
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>
答案 0 :(得分:1)
this
是属于每个函数的关键字。
在load
事件监听器中,它将是图像,而不是您的TestObj
实例。
因此,你可以
使用this.img.imgW
获取它:
function TestObj() {
var that = this;
this.img = new Image();
this.img.onload = function(){
this.imgW = this.width;
this.imgH = this.height;
that.testTheVar();
};
this.img.src = "reel_normal.PNG";
this.testTheVar = function() {
alert(this.img.imgW);
};
}
将其存储在TestObj
实例中:
function TestObj() {
var that = this;
this.img = new Image();
this.img.onload = function(){
that.imgW = this.width;
that.imgH = this.height;
that.testTheVar();
};
this.img.src = "reel_normal.PNG";
this.testTheVar = function() {
alert(this.imgW);
};
}
将事件处理程序中的this
自定义为您的TestObj
实例:
function TestObj() {
this.img = new Image();
this.img.onload = (function(){
this.imgW = this.img.width;
this.imgH = this.img.height;
this.testTheVar();
}).bind(this);
this.img.src = "reel_normal.PNG";
this.testTheVar = function() {
alert(this.imgW);
};
}
答案 1 :(得分:1)
这里有两个问题
1)范围
2)时间
范围,如其他答案中所述,指的是onload函数中的this
是Image
对象而不是TestObj,因此您需要执行以下操作:
<script type="text/javascript">
(function() {
var myTest = new TestObj();
mytest.TestTheVar();
})();
function TestObj() {
var self = this;
this.img = new Image();
this.img.onload = function(){
self.imgW = this.width;
self.imgH = this.height;
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>
时间是指您在尝试访问高度和宽度时无法假设图像已完成加载。这就是回调有利于:
<script type="text/javascript">
(function() {
var myTest = new TestObj(function() {
myTest.TestTheVar();
});
})();
function TestObj(cb) {
cb = cb || function() {};
var self = this;
this.img = new Image();
this.img.onload = function(){
self.imgW = this.width;
self.imgH = this.height;
cb();
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>