【问题标题】:Extending objects living in my namespace扩展我的命名空间中的对象
【发布时间】:2011-03-02 03:29:02
【问题描述】:

我正在开发一个小库,它正在慢慢地变得不那么小。出于这个原因,我决定将我所有的函数放入myNamespace 以避免丑陋的冲突,并将其拆分为单独的文件,以便更轻松地管理代码。不幸的是,当我这样做时,我破坏了一些以前可以工作的东西——即扩展 Array 对象的功能。那是我最初的方法不起作用:

if(myNamespace === undefined) {
  var myNamespace = {};
}

myNamespace.myArray = {
    height: 0,
    width: 0
};

myNamespace.myArray.prototype = [];  

现在当我这样做时:

testArray = myNamespace.myArray;

我好像做不到:

testArray.push("test");

我该如何解决这个问题?将代码封装在命名空间中的最佳方法是什么? 我很确定这只是我混淆了定义/实例化的对象,但我根本不知道正确的方法。

【问题讨论】:

  • 你能详细说明到底是什么坏了?您现在发布的代码实际上并没有显示任何实际功能。
  • 是的,我可能应该更清楚一点。我将编辑问题。
  • 似乎不是命名空间问题,因为无论有没有 myNamespace,该代码都不起作用。前缀。

标签: javascript inheritance namespaces


【解决方案1】:

这不是命名空间问题——它是关于你如何定义和实例化你的类。类被定义为函数,而不是对象字面量:

// define your class
ns.MyArray = function(w, h) {
   this.width = w;
   this.height = h;
};

// set the class prototype
ns.MyArray.prototype = [];

// instantiate
var a = new ns.MyArray(5,10);
a.push("Test");
a.length; // 1
a[0]; // "Test"
a.width; // 5

您所做的只是创建一个对象字面量,然后将其分配给testArray 变量,与此相同:

var o = {};
var testArray = o;
testArray == o; // true

我不确定我是否会预料到这种行为,但它看起来像分配像 {width:0, height:0} 这样的对象文字的 prototype 会添加一个带有键“原型”的普通字段 - 实际的 prototype 是还是Object

【讨论】:

  • 谢谢。我刚刚开始使用 javascript,但仍然在为它的语法而苦恼。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 2011-12-05
  • 2011-06-28
  • 2012-01-08
  • 2014-09-18
  • 1970-01-01
相关资源
最近更新 更多