我想在加载所有必需的图像时调用一个函数。图像的数量是预先知道的,因此我尝试将函数调用附加到每个图像的 onload 事件并计算它被调用的次数。
<html>
<head>
<script>
var tractor;
function Tractor()
{
this.init_graphics();
}
Tractor.prototype.init_graphics = function()
{
this.gr_max = 3;
this.load_count = 0;
this.loading_complete(); // #1 test call, works OK
this.img1 = new Image();
this.img1.onload = this.loading_complete; // #2 gets called, but gr_max = undefined, load_count = NaN
this.img1.src = "http://dl.dropbox.com/u/217824/tmp/rearwheel.gif"; //just a test image
}
Tractor.prototype.loading_complete = function()
{
this.load_count += 1;
alert("this.loading_complete, load_count = " + this.load_count + ", gr_max = " + this.gr_max);
if(this.load_count >= this.gr_max) {this.proceed();}
};
function start()
{
tractor = new Tractor();
}
</script>
</head>
<body onload="start();">
</body>
</html>
当它只是从对象的另一个函数调用时(参见#1),它的工作方式正如我所预期的那样。但是,当从 onload 事件调用它时(请参阅#2),变量会变为“未定义”或“NaN”或其他内容。发生了什么?我究竟做错了什么?我该如何让它发挥作用?
我不记得以前用 Javascript 创建过自己的对象,所以我对“我的代码出了什么问题”之类的问题深表歉意。我用了本文 http://www.phpied.com/3-ways-to-define-a-javascript-class/主要参考1.2节。
以防万一,我把相同的代码放在http://jsfiddle.net/ffJLn/ http://jsfiddle.net/ffJLn/
bind
回调的上下文:
this.img1.onload = this.loading_complete.bind(this);
See: http://jsfiddle.net/ffJLn/1/ http://jsfiddle.net/ffJLn/1/(与你的相同,但添加了此内容)
这是如何进行的解释bind
详细作品:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
基本思想是它使this
在绑定函数中等于您作为参数传递给的任何内容bind
.
另一种选择是创建一个闭包:
var self = this;
this.img1.onload = function() { self.loading_complete() };
闭包是保留对其上下文的引用的函数(事实上,javascript 中的所有函数都以这种方式工作)。所以在这里你创建一个匿名函数来保存对self
。所以这是维护上下文的另一种方法loading_complete
拥有权利this
.
See: http://jsfiddle.net/ffJLn/2/ http://jsfiddle.net/ffJLn/2/(与你的相同,但有第二种可能性)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)