使用其他方法和语法糖扩展Javascript Array

问题描述:

我需要一个数组来存储一些几何数据。我想简单地继承Array对象,并用“高度”和“宽度”(所有儿童的高度/宽度的总和)等几个新函数来扩展它,但也可以使用一些便利方法,如“insertAt”或“去掉”。使用其他方法和语法糖扩展Javascript Array

什么是最好的办法做到这一点没有修改原始数组对象(Array.prototype.myMethod)?

您可以随时直接混入更改为阵,但因为它不是每个阵列应该有可能不是最好的选择。所以让我们继承Array:

// create a constructor for the class 
function GeometricArray() { 
    this.width = 0; 
    this.height = 0; 
} 

// create a new instance for the prototype so you get all functionality 
// from it without adding features directly to Array. 
GeometricArray.prototype = new Array(); 

// add our special methods to the prototype 
GeometricArray.prototype.insertAt = function() { 
    ... 
}; 

GeometricArray.prototype.remove = function { 
    ... 
}; 

GeometricArray.prototype.add = function(child) { 
    this.push(child); 
    // todo calculate child widths/heights 
}; 

您可以使用原型将这些函数放入Array中。

要添加例如高度功能做到这一点:

Array.prototype.height = function() { 
    //implementation of height 
} 
+0

我也许应该提及的是,我的问题。我想创建一个不会修改原始数组功能的新对象。 – 2011-02-17 02:20:35

+0

那么你应该去chubbard的解决方案。 – 2011-02-17 02:26:53

+0

对我投票;-) – chubbsondubs 2011-02-17 02:29:05

您是否(可能)将Java概念应用到Javascript?

你不需要从Javascript中继承类,你只需要丰富对象

所以在我的世界的最好方法(世界挤满了人头撞方法为对象)是:

function GeometricArray() 
{ 
    var obj=[] 

    obj.height=function() { 
    // wibbly-wobbly heighty things 

    for(var i=0;i<this.length;i++) { 
     // ... 
    } 

    } 

    obj.width=function() { 
    // wibbly-wobbly widy things 
    // ... 
    } 

    // ...and on and on... 

    return obj 
}