[英]Javascript new array prototype in new object constructor
如果我做:
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"
而zt()
將返回"hello"
? (但Array.test
和Array.t
將保持undefined
)
我會更好地解釋:
Array.prototype.t="test"; Array.prototype.test = function(){ return "hello";} z=new Array("john", "andrew") console.log(z);
但這會影響所有數組。 我想要相同的東西,但是要有一個繼承Array構造函數的新構造函數Names。
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)
您可以在Names.prototype
輕松設置它
您不能只擴展Array
嗎?
class Names extends Array {
constructor(...args) {
super(...args);
this.t = "test";
}
test() { return "hello" }
}
let z = new Names("john", "andrew")
這是一個粗略的實現:
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());
您可以創建自己的擴展Array構造函數工廠,例如
(() => { 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); } })();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.