代码之家  ›  专栏  ›  技术社区  ›  Zibri

新对象构造函数中的javascript新数组原型

  •  1
  • Zibri  · 技术社区  · 6 年前

    如果我这样做了:

    Array.prototype.test = "test"
    Array.prototype.t = function() {return "hello"}
    

    每一个新的 Array 将拥有财产 test 以及方法 t 是的。

    如何在不影响所有数组的情况下执行相同的操作?

    比如:

    Names = function(arr){
      // Contacts constructor must be the same of Array 
      // but add the property test and the function t
    }
    z=new Names(["john","andrew"])
    

    以便 z.test 会回来的 "test" z.t() 会回来的 "hello" 是吗? (但是 Array.test Array.t 会留下来 undefined )

    我解释得更好:

    Array.prototype.t="test";
    Array.prototype.test = function(){ return "hello";}
    
    z=new Array("john", "andrew")
    console.log(z);

    但这会影响所有数组。 我想要相同的,但有一个继承数组构造函数的新构造函数名。

    4 回复  |  直到 6 年前
        1
  •  2
  •   Isaac    6 年前

    class Names extends Array {
      constructor(...args) {
        super(...args);
      }
    }
    
    Names.prototype.t = 'test';
    
    let z = new Names("john", "andrew")
    z.push('Amanda')
    
    console.log(z.t)
    console.log(z)

    你可以很容易地设定 Names.prototype

        2
  •  1
  •   ZER0    6 年前

    你就不能延长 Array 是吗?

    class Names extends Array {
      constructor(...args) {
        super(...args);
        this.t = "test";
      }
    
      test() { return "hello" }
    }
    
    let z = new Names("john", "andrew")
    
        3
  •  1
  •   Ivan Jeffrey Zhao    6 年前

    下面是一个粗略的实现:

    function Names(arr) {
      this.contacts = enhanceArray(arr);
    }
    
    function enhanceArray(arr) {
      arr.test = 'helloProp';
      arr.t = function() {
        return 'helloFunc'
      }
      return arr;
    }
    let z = new Names(["john", "andrew"]);
    
    console.log(z.contacts[0]);
    console.log(z.contacts.test);
    console.log(z.contacts.t());
        4
  •  0
  •   KooiInc    6 年前

    您可以创建自己的扩展数组构造函数工厂,如

    (() => {
      const myArr = XArray();
      let a = myArr(["John", "Mary", "Michael"]);
      console.log(`myArr(["John", "Mary", "Michael"]).sayHi(1): ${a.sayHi(1)}`);
      console.log("demo: myArr(1, 2, 3) throws an error");
      let b = myArr(1, 2, 3); // throws
      
      // an extended array
      function XArray() {
        const Arr = function(arr) {
          if (arr.constructor !== Array) {
            throw new TypeError("Expected an array");
          }
          this.arr = arr;
        };
        Arr.prototype = {
          sayHi: function (i) { return `hi ${this.arr[i]}`; }
        };
        return arr => new Arr(arr);
      }
    })();