3
我试图返回一个变量设置后,作为一个属性的IIFE的初始化。问题是如果我直接绑定变量,我得到一个空对象。如果我通过函数来绑定它,我会得到我想要的结果。返回一个变量作为一个属性在一个IIFE
var Application = (function(){
var localInformation = {};
function init(){
localInformation = _demoApiCall();
}
function _demoApiCall(){
// Pretend this method isn't here, and returns a complex object
return {
name: "Demo"
}
}
function doWork(){
// localInformation is properly structured here if called
}
return {
Init: init,
DoWork: doWork,
InfoProp: localInformation, // returns {}
InfoMethod: function(){
return localInformation; // returns {name:"demo"}
}
}
})();
Application.Init();
console.log(Application.InfoProp);
console.log(Application.InfoMethod());
后的文件准备好开始调用Application.Init()
,如果我叫var inf = Application.InfoMethod()
的例子只会工作,但是这将是更清洁的,如果我可以打电话给var info = Application.InfoProp
。
我试着去读JS关闭,但没有得到任何信息,为什么没有适当的引用私有变量。
我的意思写的'localInformation',但是我已经更新了我的例子有正在运行的代码。我从来没有在返回中看到过'get'关键字,如果它有效,它肯定会使用它。你介意解释一下它是什么,它比它表明的更疯狂吗? – TheGeekZn
MDN解释它比我所能做的更好:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get – lordvlad
看起来你不能在参考名称前面使用'get' 。它基本上适用于我,如果我像这样使用它: '上下文:{get Current(){ return current; }}' – TheGeekZn