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

Jea*_*eri 4 javascript inheritance prototype-chain

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

instance instanceof Rectangle --> true
instance instanceof Square    --> true
instance.area() ; // --> area is defined by Rectangle
Run Code Online (Sandbox Code Playgroud)

现在,在我的代码中,我不知道'area'函数的定义位置,我想要定义它的原型对象。我当然可以遍历原型链(未经测试)

var proto = instance ;
while( !(proto = Object.getPrototypeOf(proto)).hasOwnProperty('area') ) {}
// do something with 'proto'
Run Code Online (Sandbox Code Playgroud)

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

Aad*_*hah 5

不,没有。您必须遍历原型链:

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

现在,您只需执行以下操作:

var obj = owner(instance, "area");
console.log(obj === Rectangle);    // true
Run Code Online (Sandbox Code Playgroud)

如果instance或其原型没有属性,areaowner返回null