简体   繁体   中英

Javascript new array prototype in new object constructor

If I do:

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

Every new Array will have the property test and the method t .

How can I do the same without affecting all Arrays?

Like:

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"])

So that z.test will return "test" and zt() will return "hello" ? (but Array.test and Array.t would stay undefined )

I explain better:

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

But this affects ALL arrays. I want the same but with a new constructor Names that inherits Array constructor.

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

You can easily set it at Names.prototype

Can't you just extend Array ?

class Names extends Array {
  constructor(...args) {
    super(...args);
    this.t = "test";
  }

  test() { return "hello" }
}

let z = new Names("john", "andrew")

Here is a crude implementation:

 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()); 

You can create your own extended Array constructor factory, something like

 (() => { 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); } })(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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