[英]Why assign an IIFE to a variable?
I've been using IIFE in JavaScript
and in AngularJS
and have been using the following structure: 我一直在
JavaScript
和AngularJS
使用IIFE,并且一直在使用以下结构:
Method 1: 方法1:
//IIFE Immediately Invoked Function Expression
(function () {
}());
However, I've seen the following often where a variable is assigned to the IIFE
但是,我已经看到以下经常将变量分配给
IIFE
Method 2: 方法2:
//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {
}());
NOTE: This question is NOT about what this pattern is or what an IIFE is. 注意:这个问题不是关于这种模式是什么或IIFE是什么。 This is pertaining specifically to why one would use a return variable on an IIFE and its relation to Angular practices as well.
这与具体说明为什么人们会在IIFE上使用返回变量及其与Angular实践的关系。
In Angular Method 1 works fine, but in many of the raw JS examples I see, Method 2 is used. 在Angular方法1中工作正常,但在我看到的许多原始JS示例中,使用了方法2。 My assumption is that anything encasulated in
doStuff
will be avliable via it and callable. 我的假设是
doStuff
中的任何东西都可以通过它来实现并且可以调用。 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? 但是,我不是100%肯定2种方法的确切推理或区别,需要一些帮助才能理解何时使用不同的方法?
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). 方法#2的原因是你会在IIFE中找到返回某些东西的代码(通常但不一定是对象或函数)。 What the IIFE returns is what ends up being assigned.
IIFE返回的是最终被分配的内容。 Eg:
例如:
//IIFE Immediately Invoked Function Expression assigned to doStuff variable
var doStuff = (function () {
var privateInformationForDoStuff = 0;
function doStuff() {
console.log(++privateInformationForDoStuff);
}
return 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. IIFE确保没有任何东西可以修改
privateInformationForDoStuff
变量,它完全是doStuff
函数的私有变量。
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
};
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.