簡體   English   中英

Javascript是否有可能創建特定對象的原型Array?

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

你好,世界,

我想創建一個數組原型。

Array.prototype.foo = function(){}

但是我的原型只有在這個數組只包含像“bar”這樣的特定對象時才能應用。是否有可能在javascript中創建這樣的原型?

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

謝謝! 詹姆士

你不能。

您可以檢查當前陣列中的類型。

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

一種方法是在執行任何其他操作之前檢查您的數組是否包含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(); 

我認為你可以做類似的事情。 我能想到的最好的方法是用附加函數裝飾默認的JavaScript數組。 下面是一個顯示打印功能正常工作的示例。

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

使用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