如果我的应用程序有这样的 namespace :
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
}).apply(myApp);
然后如果我记录以下结果:
console.log(myApp.next()); //1
如何在 namespace 函数中存储变量,例如:
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
var var1 = "One";
};
}).apply(myApp);
尝试这样访问:
console.log(myApp.variableStore().var1); // Gives me an error
这可能吗,甚至是个好主意?或者我应该为本质上是全局变量的内容声明一个新的 namespace 吗?
最佳答案
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One";
return this;
};
}).apply(myApp);
只有在 variableStore()
被调用后,这样的声明才会将 var1
属性添加到 myApp
对象:
myApp.var1 //undefined
myApp.variableStore() // Object {...}
myApp.var1 //"One"
关于您的问题:您实际上不能在函数中存储变量。如果您尝试为 myApp 创建一个内部命名空间,请考虑执行以下操作:
(function() {
var id = 0;
this.next = function() {
return id++;
};
this.subNameSpace = {
init: function () {
this.var1 = "One"
return this;
}
}
}).apply(myApp);
myApp.subNameSpace.init();
myApp.subNameSpace.var1; //"One"
关于javascript - 在我的名字空间javascript中存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887156/