问题描述
我理解自我执行的匿名函数是什么,但我无法理解我将使用它们的原因以及原因。这可能是因为我经常使用jQuery。你能提供好用例的例子吗?
I understand what a self executing anonymous function is but I am having trouble understanding where I would use them and why. This could be because I often use jQuery. Could you please provide examples of good use cases?
推荐答案
基本上,一个自动执行的匿名函数(在技术上更多地称为IIFE或立即调用函数表达式)与声明命名函数然后立即调用它相同。与IIFE的唯一区别在于它没有名称,因此它只能在原地执行(不从其他地方调用),因此不会在当前名称空间中添加名称。
Basically, a self-executing anonymous function (more technically referred to as an IIFE or immediately invoked function expression) is the same as declaring a named function and then immediately calling it. The only difference with an IIFE is that is has no name so it can only be executed in place (not called from elsewhere) and consequently doesn't add a name to the current namespace.
因此,您可以随时使用一个函数内部有一堆代码,并且只需要在当前定义的上下文中调用该代码。
So, you can use one any time that having a bunch of code inside a function would be useful and when that code only ever needs to be called in the currently defined context.
一些常见的地方:
-
在任何涉及一些局部变量和一些异步的循环中操作(ajax,timeout等等),您希望在异步完成函数中为每个循环迭代分别访问这些局部变量。
In any kind of loop that involves some local variables and some asynchronous operations (ajax, timeout, etc...) where you want access to those local variables separately for each loop iteration in the asynchronous completion function.
要封装一些顶级代码,它使用自己的作用域运行一次,并拥有私有且与全局名称空间分离的局部变量。
To encapsulate some top level code that runs once with it's own scope and own local variables that are private and separate from the global namespace.
创建一个未命名的函数作用域任何原因。
To create a unnamed function scope for any reason.
示例:
循环索引(每次调用 setTimeout()
时,分别冻结循环索引):
Loop Index (freezes the loop index separately for each invocation of setTimeout()
):
for (var i = 0; i < max; i++) {
// capture the loop index into in a closure
(function(index) {
setTimeout(function() {
console.log(index);
}, 2000);
})(i);
}
顶级代码封装(创建私有但持久的变量,不在全局范围):
Top Level Code Encapsulation (creates private, but persistent variable that is not in the global scope):
(function() {
var cntr = 0;
window.getUniqueId = function() {
return ++cntr;
};
})();
在代码中创建本地可用的快捷变量,否则这些变量将成为顶级范围。
Create locally available shortcut variables in code that would otherwise be top level scope.
function Dictionary(initialData) {
// call parent constructor
Set.apply(this, arguments);
}
(function() {
// inherit from Set
var proto = Dictionary.prototype = new Set();
var base = Set.prototype;
// Set constructor back to us
proto.constructor = Dictionary;
// override of the base class .add()
// add(key, value)
// add(Dictionary)
// add({key1: value1, key2: value2})
proto.add = function(arg1, arg2) {
if (arg1 instanceof Set) {
// call base class to just add another Set
base.add.call(this, arg1);
} else if (typeof arg1 === "object") {
// cycle through the object and add all properties/values to the Set
for (var prop in arg1) {
if (arg1.hasOwnProperty(prop)) {
this._add(prop, arg1[prop]);
}
}
} else if (typeof arg2 !== "undefined") {
// must be add(key, value)
this._add(arg1, arg2);
}
return this;
}
proto.get = function(key) {
return this.data[key];
}
// See rest of code here: https://github.com/jfriend00/Javascript-Set/blob/master/dictionary.js
})();
这篇关于JavaScript自行执行匿名函数有哪些好的用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!