下面是一个函数的源代码,它将图像预加载到页面上,作者在一些注释中添加了解释代码如何工作的内容,但我仍然不完全理解它。具体来说,他声称这个函数的返回值是一个带有“done()”方法的空对象,该方法调用预定义的匿名函数“postaction()”。这段代码的用户是否应该将他/她自己的代码输入到第2行的空postaction函数中?如果这就是它的工作原理,那么返回对象中的“postaction = f || postaction”是做什么的?javascript中的匿名函数和空返回对象
的源代码:
function preloadimages(arr){
var newimages=[], loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost(){
loadedimages++
if (loadedimages==arr.length){
postaction(newimages) //call postaction and pass in newimages array as parameter
}
}
for (var i=0; i<arr.length; i++){
newimages[i]=new Image()
newimages[i].src=arr[i]
newimages[i].onload=function(){
imageloadpost()
}
newimages[i].onerror=function(){
imageloadpost()
}
}
return { //return blank object with done() method
done:function(f){
postaction=f || postaction
//remember user defined callback functions to be called when images load
}
}
}
链接到作者的页面:http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml
如果对象是空的,它将不包含done方法。 – 2012-08-01 13:54:50
在作者的页面上,他将其称为空对象 – imkendal 2012-08-01 13:55:45
看起来他错误地使用术语“空白对象”来表示[object literal](https://developer.mozilla.org/en/JavaScript/Guide/Values, _Variables,_and_Literals#Object_literals)。 – 2012-08-01 13:57:43