[英]javascript: find the prototype object to which a property belongs
我有一个来自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'
但是,我想知道是否有更好/更快的方法来获取函数所属的原型对象?
不,没有。 您必须遍历原型链:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.