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

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

问题描述

可能的重复:
自执行函数的目的是什么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?

推荐答案

根据我的个人经验,除了使用匿名函数来引入作用域之外,我还在 for 循环中使用它来进行闭包.当 DOM 元素需要存储其计数并且您无权访问 jQuery 等库时,这会很有用.

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.

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

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 );
    };
}

这将警告 99,因为计数器当前为 99.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);
}

这里保持i的值并显示正确的计数.

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

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

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