Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在这种情况下如何使用闭包?_Javascript_Closures - Fatal编程技术网

Javascript 在这种情况下如何使用闭包?

Javascript 在这种情况下如何使用闭包?,javascript,closures,Javascript,Closures,查看onComplete结果:当前项。名称始终为rty,但应为(1/2):qwe,(2/2):rty。我知道使用闭包可以解决这个问题,但不知道如何解决 稍微更新一下 另一件需要注意的事情是,在逻辑中,onComplete处理程序是在加载列表中的最后一个图像时启动的,而不是在加载所有图像时启动的。您希望i由所有onload处理程序递增,因此不要为该变量创建闭包。否则,所有处理程序都会增加自己的i,而不是共享值。而且,self独立于图像。但是,项在每个处理程序中应不同: 我需要将所有VAR传递给Cl

查看
onComplete
结果:当前
项。名称始终为
rty
,但应为(1/2):
qwe
,(2/2):
rty
。我知道使用闭包可以解决这个问题,但不知道如何解决

稍微更新一下


另一件需要注意的事情是,在逻辑中,
onComplete
处理程序是在加载列表中的最后一个图像时启动的,而不是在加载所有图像时启动的。

您希望
i
由所有
onload
处理程序递增,因此不要为该变量创建闭包。否则,所有处理程序都会增加自己的
i
,而不是共享值。而且,
self
独立于图像。但是,
项在每个处理程序中应不同:


我需要将所有VAR传递给Close吗?(i,total,item)?不,您只需要传递可以由外部代码更改的变量,就可以“冻结”它们,所以(意思是您关于逻辑的通知),我如何才能正确地完成它?如果您使用pimvdb答案中的代码,您应该可以接受它,因为只有在onload处理程序中i才递增,从而成为加载项的计数器。
Items = function(){
    this.onProgress = function(current, total, item){};
    this.onComplete = function(){};
}

Items.prototype.add = function(items){

    var self = this;
    var i = 0, total = items.length;

    while(items.length){
        var item = items.shift();
        var img = new Image();

        // closure should be somewhere here...
        img.onload = function(){

            self.onProgress(++i, total, item);

            i == total && self.onComplete();

        }

        img.src = item.src;

    }

}


var items = new Items();

items.onProgress = function(current, total, item){
    console.log('(%d/%d) item `%s` loaded', current, total, item.name);
    // => (1/2) item `rty` loaded
    // => (2/2) item `rty` loaded
}

items.onComplete = function(){
    console.log('Loading items complete.')
}

items.add([
    {name: 'qwe', src: '../qwe.png'},
    {name: 'rty', src: '../rty.png'}
]);
img.onload = (function(currentI) {
    // here currentI will stay with the value the i had in the moment of creating this handler
})(i)
img.onload = (function(item){
    return function(){
        self.onProgress(++i, total, item);
        i == total && self.onComplete();
    }
})(item);