问题描述
我试图在IIFE初始化后返回一个变量集作为属性。问题是如果我直接绑定变量,我得到一个空对象。如果我通过函数绑定它,我得到我想要的结果。
I am trying to return a variable set after the initialization of an IIFE as a property. The issue is if I bind the variable directly, I get an empty object. If I bind it through a function, I get my desired result.
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());
最初的c之后在文档准备好的所有 Application.Init()
上,该示例仅在我调用 var inf = Application.InfoMethod()$ c $时才有效c>,但如果我可以打电话给
var info = Application.InfoProp
,那就更清洁。
After initially calling Application.Init()
on document ready, the example will only work if I call var inf = Application.InfoMethod()
, however it would be much cleaner if I could call var info = Application.InfoProp
.
我'我试图阅读JS闭包,但没有得到任何关于为什么没有适当的私有变量引用的信息。
I've tried to read up on JS Closures, but haven't gotten any information into why there would be no proper reference to the private variable.
推荐答案
我想你的意思是在你的退货对象中写 localInformation
。
I guess you meant to write localInformation
in your returned object.
问题是你是将 localInformation
变量名称重新分配给新对象。
The problem is that you are re-assigning the localInformation
variable name to a new object.
localInformation = _demoAPICall()
意味着你的 InfoProp
属性指向 localInformation
(空对象)的初始值,而在函数内,您获得 localInformation的最新值
。
Meaning that your InfoProp
property points to the initial value of localInformation
(the empty object), while within the function, you get the latest value of localInformation
.
您有两种选择:
1)扩展现有对象,而不是将变量名称分配给新一个:
1) Extend the existing object instead of assigning the variable name to a new one:
extend(localInformation, _demoApiCall())
你可以使用jQuery的扩展,或者来自lodash的扩展,或任何其他实现都可以。
You cann use jQuery's extend, ot the one from lodash, or any other implementation will do.
2)使用getter方法
2) use a getter method
return {
Init: Init,
get InfoProp () { return information },
....
}
这篇关于将变量作为IIFE中的属性返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!