0
这里是什么即时试图做一个简单的版本:javascript onload如何在实例中工作?
<script type="text/javascript">
function Example(position) {
this.position = position;
instance = this;
img = new Image();
img.src = 'http://www.gazette-ariegeoise.fr/IMG/jpg/test.jpg';
console.log(this.position);
//logs as expected 1 than 2 on the second
img.onload = function() {
console.log(instance.position);
//logs 2 twice
}
}
ex1 = new Example(1);
ex2 = new Example(2);
</script>
莫名其妙的onload功能记录实例2次的位置,
为什么呢?
我认为他应该使用'this.instance'而不是实例。 – PDKnight
@PDKnight - 在事件处理程序中?这是行不通的。 'this'将是图像,而不是'Example'实例。 – Quentin
如果他将onload函数绑定到当前实例(新示例),则会生效。 – PDKnight