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

javascript: find the prototype object to which a property belongs

本文关键字:原型 对象 查找 属性 javascript      更新时间:2023-09-26

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

如果instance或其原型不具有属性area,则owner返回null

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

在您的情况下,我不想麻烦处理原型链,您可以将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