简体   繁体   English

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

[英]Extending a Javascript Array with additional methods and syntactic sugar

I need an array to store some geometrical data. 我需要一个数组来存储一些几何数据。 I would like to simply inherit from the Array object and than extend it with a few new functions like "height" and "width" (sum of all children's heights/widths), but also with a few convenience methods like "insertAt" or "remove". 我想简单地从Array对象继承而不是使用一些新函数来扩展它,比如“height”和“width”(所有孩子的高度/宽度的总和),还有一些方便的方法,如“insertAt”或“去掉”。

What is the best way to do it without modifying the original Array object (Array.prototype.myMethod)? 修改原始Array对象(Array.prototype.myMethod)的情况下 ,最好的方法是什么?

You can always mixin your changes directly into Array, but that might not be the best choice given that it's not something every array should have. 您可以随时将更改直接混合到Array中,但这可能不是最佳选择,因为它不是每个数组都应该具有的。 So let's inherit from 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
};

Are you (maybe) applying Java concepts to Javascript? 您(可能)将Java概念应用于Javascript吗?

You don't need to inherit from classes in Javascript, you just enrich objects . 您不需要继承Javascript中的类,只需丰富 对象

So the best way in my world (a world full of people head-butting methods into objects) is: 因此,在我的世界中最好的方式(一个充满了人们头脑对接方法的世界)是:

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
}

You could use prototyping to put those functions in Array. 您可以使用原型设计将这些函数放入Array中。

To add the height function for example do this: 要添加高度函数,例如,请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM