gpt4 book ai didi

javascript:查找属性所属的原型(prototype)对象

转载 作者:行者123 更新时间:2023-12-03 12:22:13 26 4
gpt4 key购买 nike

我有一个 Square 的实例,它继承自 Rectangle

instance instanceof Rectangle --> true
instance instanceof Square --> true
instance.area() ; // --> area is defined by Rectangle

现在,在我的代码中,我不知道“区域”函数是在哪里定义的,我想要定义它的原型(prototype)对象。当然可以遍历原型(prototype)链(未测试)
var proto = instance ;
while( !(proto = Object.getPrototypeOf(proto)).hasOwnProperty('area') ) {}
// do something with 'proto'

但是,我想知道是否有更好/更快的方法来获取函数所属的原型(prototype)对象?

最佳答案

不,没有。你必须遍历原型(prototype)链:

function owner(obj, prop) {
var hasOwnProperty = Object.prototype.hasOwnProperty;
while (obj && !hasOwnProperty.call(obj, prop))
obj = Object.getPrototypeOf(obj);
return obj;
}

现在您只需执行以下操作:
var obj = owner(instance, "area");
console.log(obj === Rectangle); // true

如果 instance或其原型(prototype)没有属性 area然后 owner返回 null .

关于javascript:查找属性所属的原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18248799/

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