javascript: find the prototype object to which a property belongs

爱⌒轻易说出口 提交于 2019-11-30 17:26:45

问题


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

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 ?


回答1:


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;
}

Now you simply do:

var obj = owner(instance, "area");
console.log(obj === Rectangle);    // true

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




回答2:


Replying to you comment: What you essentially seem to want is to call a function of the base class inside the overriding function of an inherited class.

I wouldn't bother with the prototype chain in your case, you can just build base into your inheritance model:

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



来源:https://stackoverflow.com/questions/18248799/javascript-find-the-prototype-object-to-which-a-property-belongs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!