[removed] find the prototype object to which a property belongs

前端 未结 2 1480
清酒与你
清酒与你 2021-01-06 06:21

I have an instance from Square which inherits from Rectangle

instance instanceof Rectangle --> true
instance instanceof Square    --> true
instance.are         


        
2条回答
  •  耶瑟儿~
    2021-01-06 06:52

    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.

提交回复
热议问题