javascript:找到属性所属的原型对象 [英] javascript: find the prototype object to which a property belongs

查看:97
本文介绍了javascript:找到属性所属的原型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an instance from Square which inherits from Rectangle

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

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

Now, in my code I don't know where the 'area' function is defined and I want the prototype object which defines it. Of course I can traverse the prototype chain (not tested)

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

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

However, I was wondering if there is a better/faster way to get the prototype object to which a function belongs ?

推荐答案

没有。没有。你必须遍历原型链:

No. There isn't. You have to traverse the prototype chain:

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 或其原型没有属性区域然后所有者返回 null

If instance or its prototypes do not have the property area then owner returns null.

这篇关于javascript:找到属性所属的原型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆