If I run this piece of JavaScript code in Firefox:
function Human() {
}
function Engineer(diploma) {
this.diploma = diploma;
}
Engineer.prototype = new Human();// Line A1
Engineer.prototype.constructor = Engineer;
Engineer.prototype.getDiploma = function() {
alert(this.diploma);
};
var engineer = new Engineer("Bridges and Roads");
engineer.getDiploma();
var human = new Human();
human.getDiploma(); // Line A2
the line marked as "A2" will generate an error in the Firefox console:
TypeError: human.getDiploma is not a function
Note also that, on line A1, I've used "new" to simulate that Engineer inherits from Human. This can be tested in the following JSFiddle:
Now I change the A1 line like so:
function Human() {
}
function Engineer(diploma) {
this.diploma = diploma;
}
Engineer.prototype = Human.prototype;// Line B1
Engineer.prototype.constructor = Engineer;
Engineer.prototype.getDiploma = function() {
alert(this.diploma);
};
var engineer = new Engineer("Bridges and Roads");
engineer.getDiploma();
var human = new Human();
human.getDiploma(); // Line B2
Note that A1 line has been replaced by the B1 line. The rest of the code is the same. This time, if I run it, there's no error in the Firefox console, but I will get one alert saying "Bridges and Roads" (which is the call to engineer.getDiploma()), and another alert saying "undefined" (which is the result of the B2 line). This can also be checked on JSFiddle, here:
My question is: why this difference? What's the difference between doing this:
Engineer.prototype = new Human();
and this:
Engineer.prototype = Human.prototype;