[英]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
. 每个新的
Array
都将具有属性test
和方法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"
? 这样
z.test
将返回"test"
而zt()
将返回"hello"
? (but Array.test
and Array.t
would stay undefined
) (但
Array.test
和Array.t
将保持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.
我想要相同的东西,但是要有一个继承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)
You can easily set it at Names.prototype
您可以在
Names.prototype
轻松设置它
Can't you just extend Array
? 您不能只扩展
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 您可以创建自己的扩展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.