gpt4 book ai didi

Javascript 是否可以创建特定对象的原型(prototype)数组?

转载 作者:行者123 更新时间:2023-11-30 11:24:00 25 4
gpt4 key购买 nike

Hello World

我想创建一个数组的原型(prototype)。

Array.prototype.foo = function(){}

但我的原型(prototype)必须仅在该数组仅包含特定对象(如“bar”)时才适用是否可以在 javascript 中创建这样的原型(prototype)? :

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

关于Javascript 是否可以创建特定对象的原型(prototype)数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com