“自我调用匿名函数”的目的在于, [英] The purpose of "Self Invoking Anonymous Functions"

查看:99
本文介绍了“自我调用匿名函数”的目的在于,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


希望这是一个非常直接的问题:

使用自调用匿名函数的目的是什么?仅仅是为了防止用变量等污染全球范围?或者是否还有其他优势?

除了使用匿名函数来引发范围之外,我也用它来封闭循环。当一个DOM元素需要存储它的计数并且你不能访问像jQuery等库时,这是非常有用的。



假设你有一个100 DIV 元素。点击第一个 DIV 元素应该提醒1,同样点击第56个div元素应该提醒56.



这些元素,你通常做这样的事情

  //假设myElements是前面提到的div元素的集合

for(var i = 0; i <100; ++ i){
myElements [i] .onclick = function(){
alert('您点击了:'+ i) ;
};



$ b $ p
$ b

这将提醒99,因为计数器当前是99. <

但是,当使用匿名函数解决问题时,

  for(var i = 0; i <100; ++ i){
(function(count){
myElements [count] .onclick = function(){
alert('您点击了:'+ count);
};
})(i);

这里 i 被维护,并显示正确的计数。


Possible Duplicate:
What is the purpose of a self executing function in javascript?

Hopefully quite a straight forward question:

What is the purpose of using self invoking anonymous functions? Is it simply to prevent "polluting" the global scope with variables etc.? Or are there other advantages to using them?

解决方案

Out of my personal experience, other than using anonymous functions for inducing a scope, I have also used it in for-loops for closure. This can be useful when a DOM element needs to store its count and you don't have access to libraries like jQuery etc.

Let's say you have a 100 DIV elements. Clicking the first DIV element should alert 1, similarly clicking the 56th div element should alert 56.

So when creating these elements, you normally do something like this

// Assume myElements is a collection of the aforementioned div elements

for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = function() {
        alert( 'You clicked on: ' + i );
    };
}

This will alert 99, as the counter is currently 99. The value of i is not maintained here.

However, when an anonymous function is used to tackle the problem,

for (var i = 0; i < 100; ++i) {
    (function(count){
     myElements[count].onclick = function() {
         alert( 'You clicked on: ' + count );
     }; 
    })(i);
}

Here the value of i is maintained and the correct count is displayed.

这篇关于“自我调用匿名函数”的目的在于,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆