【问题标题】:using a single global namespace, how to access properties/methods of the namespace from the methods of tools?使用单个全局命名空间,如何从工具的方法访问命名空间的属性/方法?
【发布时间】:2013-03-16 03:56:59
【问题描述】:

当使用单个全局命名空间构建各种工具时,我们如何从工具的方法中访问命名空间对象的属性或方法,而不是在外部进行访问?

OT,“我们的工具”成为命名空间。

我们可以这样做:

var OT = function(){ // Closure
   var Turkey = 'Im a Turkey!';
   return this;
}();

var OT = { // Object Literal
   Turkey:'Im a Turkey!'
};

无论哪种情况,我们都将我们的工具添加到OT 对象中,例如:

OT.GridInterface = function (){
   // A Grid tool
   this.DoSomething();
}
OT.GridInterface.prototype = new OT.BaseInterface();


OT.GridInterface.prototype.DoSomething = function(){
   console.log(Turkey); // undefined
   console.log(OT.Turkey); // undefined with Closure, works with Obj Literal*
   console.log(this.Turkey); // undefined
}

// * This goes around the outside to get the property publicly rather than up through the inside.

似乎每个工具在技术上都是OT 的方法,并且该方法的方法应该能够访问命名空间的Turkey 属性,因为内部函数应该能够访问外部的属性函数?

我的目标是能够将共享配置变量以及一些实用方法添加到OT,所有OT 方法的工具都可以使用。理想情况下,这些工具和属性应该可以从这些工具中读取/使用,但它们是不可变的。

【问题讨论】:

    标签: javascript inheritance closures prototypal-inheritance


    【解决方案1】:

    您可以阅读here,它解释了有关 JavaScript 中私有成员的更多信息。

    基本上,你问的是不可能的。

    要么所有函数都必须在闭包中定义,要么Turkey 需要公开。

    【讨论】:

      猜你喜欢
      • 2012-08-06
      • 1970-01-01
      • 2012-03-05
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多