【问题标题】:Extending a Javascript Array with additional methods and syntactic sugar使用其他方法和语法糖扩展 Javascript 数组
【发布时间】:2011-02-17 02:10:39
【问题描述】:

我需要一个数组来存储一些几何数据。我想简单地从 Array 对象继承,而不是用一些新的函数来扩展它,比如“height”和“width”(所有孩子的高度/宽度的总和),还有一些方便的方法,比如“insertAt”或“删除”。

修改原始 Array 对象 (Array.prototype.myMethod) 的最佳方法是什么?

【问题讨论】:

    标签: javascript arrays inheritance


    【解决方案1】:

    您始终可以将更改直接混合到数组中,但这可能不是最佳选择,因为它不是每个数组都应该具有的。所以让我们从 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
    };
    

    【讨论】:

    • 很抱歉,它似乎对我不起作用。那是我最初的方法,但不知何故,当我在“GeometricArray”上调用任何 Array 方法时,我得到:“TypeError: Object # has no method 'push'”我很确定这是我做错了什么。 :-)
    • @piotr 我今天早些时候演示了相同的技术。也许另一个例子会有所帮助:stackoverflow.com/questions/5020954/…
    • 我肯定会在比现在更简单的代码上再次尝试使用它,以减少其他东西搞砸结果的机会。
    【解决方案2】:

    您是否(可能)将 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
    }
    

    【讨论】:

    • 我接受了上述答案,因为它更接近我的预期,但这个解决方案同样有效。我很想看到有人解释这两种解决方案的优缺点。
    • prototypethis 都是 new 运算符在 javascript 中所做的事情的一部分。只要您是编写构造函数的人,这是一种过度思考,几乎没有存在的意义。
    • 也就是说,除非您要丰富 Core 对象,例如 ArrayObject。在这种情况下,您不能覆盖构造函数,但使用 prototype 无论如何您都可以丰富这些对象。 (只是,它出来了,这种方式真的很容易把自己打死)我不是最新的,但我想某些浏览器可能会将某些核心对象的丰富视为安全威胁
    【解决方案3】:

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

    要添加高度功能,例如这样做:

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

    【讨论】:

    • 我可能应该在我的问题中提到这一点。我想创建一个不会修改原始 Array 功能的新对象。
    • 那么您可能应该采用 chubbard 的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2017-07-12
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多