问题描述
在JavaScript中的模块模式中,立即调用的函数表达式(也称为自执行匿名函数)用作返回对象的自执行函数。
自执行函数如何隐藏私有变量,只公开返回的对象。为什么这不会发生在正常的JavaScript函数?
所以在下面的迷你模块中,为什么我们不能实现相同的封装概念,而不使用surrounding()()?
In the module pattern in JavaScript "Immediately-Invoked Function Expressions" (also known as self-executing anonymous functions) are used as self executing functions that return an object.How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function?So in the following mini module, why could we not achieve the same concept of encapsulation without the enclosing ()()?
var Module = (function () {
var privateVariable = "foo",
privateMethod = function () {
alert('private method');
};
return {
PublicMethod: function () {
alert(privateVariable);
privateMethod();
}
};
})();
推荐答案
这是正常的JavaScript函数。
It does happen with normal JavaScript functions.
function MakeModule() {
var privateVariable = "foo",
privateMethod = function () {
alert('private method');
};
return {
PublicMethod: function () {
alert(privateVariable);
privateMethod();
}
};
}
var Module = MakeModule();
会很好。
唯一的区别是匿名函数引入一个较少的全局变量,并允许自己被垃圾收集,而 MakeModule
不能被收集,除非显式地 delete
d。作者。
The only difference is that the anonymous function introduces one less global variable and allows for itself to be garbage collected while MakeModule
can't be collected unless explicitly delete
d by the author.
这篇关于为什么在Javascript模式模式中使用自动执行的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!