Javascript直接使用函数并使用从另一个函数返回的函数
纯粹出于好奇,我看到了下面这样的代码Javascript直接使用函数并使用从另一个函数返回的函数,javascript,Javascript,纯粹出于好奇,我看到了下面这样的代码 let GlobalActions = function () { let doSomething= function () { //Do Something }; return { doSomething: function () { doSomething() } }; }(); GlobalActions.doSomething(); 起初,
let GlobalActions = function () {
let doSomething= function () {
//Do Something
};
return {
doSomething: function () {
doSomething()
}
};
}();
GlobalActions.doSomething();
起初,我认为这是关于范围的,可能外部的var声明变量在初始化后无法从内部的每个函数访问;然而,事实并非如此
然后我开始思考做上面的而不是下面的有什么好处
let GlobalActions = {
doSomething: function () {
//Do Something
};
};
GlobalActions.doSomething();
在我看来是
本质上,返回的对象为整个类提供API接口。然后,我们可以选择什么是公开的,什么是私有的。例如
var myRevealingModule = (function () {
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
myRevealingModule.setName( "Paul Kinlan" );
这是用于私有成员的所谓模块模式,请参阅。这可能是其中一些的复制品。publicVar不是公共的,它是私有的。它是由特权函数publicSetName设置的。所以它与使用类完全相同?