问题描述
我一直在JavaScript
和AngularJS
中使用IIFE,并一直使用以下结构:
I've been using IIFE in JavaScript
and in AngularJS
and have been using the following structure:
方法1:
//IIFE Immediately Invoked Function Expression
(function () {
}());
但是,我经常看到以下情况,其中将变量分配给IIFE
However, I've seen the following often where a variable is assigned to the IIFE
方法2:
//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {
}());
注意:关于此模式是什么或IIFE是否的问题.这与为什么要在IIFE上使用返回变量 及其与Angular实践的关系有关.
NOTE: This question is NOT about what this pattern is or what an IIFE is. This is pertaining specifically to why one would use a return variable on an IIFE and its relation to Angular practices as well.
在Angular方法1中工作正常,但是在我看到的许多原始JS示例中,都使用了方法2.我的假设是doStuff
中包含的任何内容都可以通过它进行调用.但是,我不确定这两种方法的确切推理或区别是100%不确定,需要一些帮助来了解何时使用不同的方法吗?
In Angular Method 1 works fine, but in many of the raw JS examples I see, Method 2 is used. My assumption is that anything encasulated in doStuff
will be avliable via it and callable. However, I'm not 100% sure on the exact reasoning or distinction between the 2 methods and need some help understanding when to use the different methods?
推荐答案
方法2的原因是,您会在IIFE中找到返回的代码(通常,但不一定,对象或函数). IIFE返回的是最终被分配的东西.例如:
The reason for Method #2 is that you'll find code within the IIFE that returns something (typically, but not necessarily, an object or a function). What the IIFE returns is what ends up being assigned. E.g.:
//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {
var privateInformationForDoStuff = 0;
function doStuff() {
console.log(++privateInformationForDoStuff);
}
return doStuff;
}());
在那里,变量最终是对函数的引用,该函数每次被调用时,都会给我们一个比上一次更高的数字. IIFE可以确保没有任何东西可以修改privateInformationForDoStuff
变量,因为它完全是doStuff
函数的私有变量.
There, the variable ends up being a reference to a function that, each time it's called, gives us a number higher than the previous time. The IIFE is there to ensure that nothing can modify the privateInformationForDoStuff
variable, it's entirely private to the doStuff
function.
此方法的常见用途是创建具有各种功能的对象,有时称为模块,这些对象可能还具有仅在模块"内共享的私人信息:
The common use of this is to create objects with various functions on them, sometimes called modules, which might also have private information that's only shared within the "module":
var MyApp = (function() {
var privateModuleInformation;
var morePrivateModuleInformation;
// ...
function doThis() {
// ...
}
function doThat() {
// ...
}
function doTheOther() {
// ...
}
return {
doThis: doThis,
doThat: doThat,
doTheOther: doTheOther
};
})();
这篇关于为什么将IIFE分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!