简体   繁体   English

Javascript是否有可能创建特定对象的原型Array?

[英]Javascript Is it possible to create a prototype Array of particular object?

Helloworld, 你好,世界,

I want to create a prototype of array. 我想创建一个数组原型。

Array.prototype.foo = function(){}

But my prototype must apply only if this array contain only a specific object like "bar" Is it possible to create a prototype like this in javascript? 但是我的原型只有在这个数组只包含像“bar”这样的特定对象时才能应用。是否有可能在javascript中创建这样的原型? :

Array<bar>.prototype.foo = function(){}

Thank you! 谢谢! James 詹姆士

No, you can not. 你不能。

You can check for the types in your current array. 您可以检查当前阵列中的类型。

 class Bar {} Array.prototype.foo = function() { if (this.some((n) => !(n instanceof Bar))) throw new Error('Incompatible type.'); console.log('called'); } let array = [1, 2]; try { array.foo(); } catch(e) { console.log(e.message); } array = [new Bar(), new Bar()]; array.foo(); 

One way to do this would be to check if your array contains bar before doing anything else, and stopping if it does not : 一种方法是在执行任何其他操作之前检查您的数组是否包含bar ,如果不执行则停止:

  Array.prototype.foo = function(){ if (this.indexOf('bar') === -1) { throw "The array must contain bar"; } // do what must be done console.log("all good"); } var rightOne = ['john', 'jane', 'bar']; var wrongOne = ['john', 'jane']; rightOne.foo(); wrongOne.foo(); 

I think that you can do something similar. 我认为你可以做类似的事情。 The best way that I can think to do is it to decorate the default JavaScript array with an additional function. 我能想到的最好的方法是用附加函数装饰默认的JavaScript数组。 Below is an example showing a print function working. 下面是一个显示打印功能正常工作的示例。

 let test = ['a', 'b', 'c']; function decoratedArray(args) { let decorated = [...args]; decorated.print = () => { decorated.forEach((arg) => { console.log(arg); }); } return decorated; } test = decoratedArray(test); test.print(); 

With ES6 classes you could subclass an Array to get all it's internal methods, and add your own methods to it without modifying the native Array prototype. 使用ES6类,您可以继承Array以获取其所有内部方法,并在不修改本机Array原型的情况下向其添加自己的方法。

 class Bar { constructor(id) { this.id = id } } class Foo extends Array { constructor(...args) { super(...args) } foo() { if (this.some(x => x instanceof Bar === false)) throw new Error('Foo can only contain Bar instances') console.log('All items are Bars') return this } } const pass = new Foo(new Bar(1), new Bar(2)) const fail = new Foo(new Bar(3), new Object) pass.foo() fail.foo() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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