我有一个 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/