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

Pio*_*rek 4 javascript arrays inheritance

我需要一个数组来存储一些几何数据.我想简单地继承Array对象,然后用一些新函数扩展它,比如"height"和"width"(所有孩子的高度/宽度的总和),还有一些方便的方法,如"insertAt"或"去掉".

修改原始Array对象(Array.prototype.myMethod)的情况下,最好的方法是什么?

chu*_*ubs 5

您可以随时将更改直接混合到Array中,但这可能不是最佳选择,因为它不是每个数组都应该具有的.所以让我们从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
};
Run Code Online (Sandbox Code Playgroud)