Javascript Inheritance
var Vehicle = function() {};
Vehicle.prototype.drive = function() { console.log('vrooom...'); };
var Car = function() {};
Car.prototype = new Vehicle();
Car.prototype.honk = function() { console.log('honk honk'); };
var myCar = new Car();
myCar.honk(); // outputs "honk honk" myCar.drive(); // outputs "vrooom..."
IN JAVASCRIPT, INHERITANCE RUNS THROUGH A CHAIN OF PROTOTYPES.
The prototype of the Vehicle constructor has a function drive. Here is what happens when the myCar object is asked to drive():
- The interpreter looks for a drive method within the myCar object, which does not exist - The interpreter then asks the myCar object for its prototype, which is the prototype of its constructor Car - When looking at Car.prototype, the interpreter sees a vehicle object which has a function honk attached, but no drive function - Thus, the interpreter now asks this vehicle object for its prototype, which is the prototype of its constructor Vehicle - When looking at Vehicle.prototype, the interpreter sees an object which has a drive function attached - the interpreter now knows which code implements the myCar.drive() behaviour, and executes it
-Manuel Kiessling















