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
You can find the object from which a property is inherited by traversing the prototype chain:
Then you can do