Determine origin of method in prototype chain

2019-05-10 13:20发布

Lets say that i have the following prototype-chain.

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();

I'm iterating over the car-object with a for-loop and want to determine which object the method origins from like so:

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

The outcome i am hoping for is a list of the methods origin like so:

Vehicle
Vehicle
Car

1条回答
太酷不给撩
2楼-- · 2019-05-10 14:10

You can find the object from which a property is inherited by traversing the prototype chain:

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

Then you can do

for (var p in car)
    console.log(p, origin(car, p), origin(car, p).constructor.name)
honkHorn, {…}, Car
drive, {…}, Vehicle
turnOn, {…}, Vehicle
查看更多
登录 后发表回答