javascript - 在我的名字空间javascript中存储变量

标签 javascript

如果我的应用程序有这样的 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/

相关文章:

javascript - 绕过 ASP.NET 中的查询字符串验证(XSS 预防)

javascript - sizzle.js 中的正则表达式如何工作?

javascript - 作为数组附加到数组内

javascript - Threejs Vector3 取消投影相机

javascript - 具有特定类的最接近的 div

javascript - 为什么函数执行后事件监听器不立即被删除?

javascript - 使用D3.js找到SVG路径的质心

javascript - 单个路由中的 js-data 多个模型

javascript - Ajax 调用后页面卡住

javascript - 如何将 Chosen 合并到我的 React 项目中?