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

时间:2013-08-15 08:20:50

标签: javascript inheritance prototype-chain

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

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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或其原型没有属性area,则owner会返回null

答案 1 :(得分:1)

回复你的评论:你基本上想要的是在继承类的重写函数中调用基类的函数。

我不打算在你的情况下使用原型链,你可以在你的继承模型中构建base

function Rectangle() {}
Rectangle.prototype.area = function () {
    console.log("rectangle");
};

//setting up inheritance
function Square() {}
Square.prototype = Object.create(Rectangle.prototype);
Square.prototype.base = Rectangle.prototype;

Square.prototype.area = function () {
    this.base.area();
    console.log("square");
};

var square = new Square();
square.area();

<强> FIDDLE

相关问题