确定原型链中方法的起源

时间:2015-04-24 14:21:33

标签: javascript oop prototype

假设我有以下原型链。

function Vehicle() {}
Vehicle.prototype.drive = function() { console.log("I'm driving"); };
Vehicle.prototype.turnOn = function() { console.log("Wrom wrom"); }; 

function Car() {}
Car.prototype = new Vehicle();
Car.prototype.honkHorn = function() { console.log("*loud sound*"); };

var car = new Car();

我使用car循环遍历for - 对象并想要确定方法来自哪个对象,如下所示:

for (var prop in car) {
    console.log(car[prop].nameOfItsOrigin);
}

我希望的结果是方法来源列表如下:

Vehicle
Vehicle
Car

1 个答案:

答案 0 :(得分:3)

您可以通过遍历原型链找到继承属性的对象:

function origin(obj, prop) {
    for (; obj != null; obj=Object.getPrototypeOf(prop))
        if (Object.prototype.hasOwnProperty.call(obj, prop))
            return obj;
    return obj;
}
// or, recursively:
function origin(obj, prop) {
    if (obj == null || Object.prototype.hasOwnProperty.call(obj, prop))
        return obj;
    return origin(Object.getPrototypeOf(obj), prop);
}

然后你可以做

for (var p in car)
    console.log(p, origin(car, p), origin(car, p).constructor.name)
honkHorn, {…}, Car
drive, {…}, Vehicle
turnOn, {…}, Vehicle