我有一个来自 Square 的实例,它继承自 Rectangle
instance instanceof Rectangle --> true
instance instanceof Square --> true
instance.area() ; // --> area is defined by Rectangle
现在,在我的代码中,我不知道“区域”函数在哪里定义,我想要定义它的原型对象。当然我可以遍历原型链(未测试)
var proto = instance ;
while( !(proto = Object.getPrototypeOf(proto)).hasOwnProperty('area') ) {}
// do something with 'proto'
但是,我想知道是否有更好/更快的方法来获取函数所属的原型对象?
不,没有。你必须遍历原型链:
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
If instance
或者它的原型不具备该属性area
then owner
回报null
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)