Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book:
function Car() {
var self = this;
self.type = "Car"
self.go = function() {
console.log("Going...");
};
};
Toyota = function() { console.log("Original called"); };
Toyota.prototype = new Car();
Toyota.prototype.constructor = function() {
var self = this;
self.type = "Toyota";
self.go = function() {
console.log("A Toyota car is going...");
}
};
Toyota.prototype.isJapaneseCar = true;
function TestCar() {
console.log("Toyota.prototype.constructor: " + Toyota.prototype.constructor);
var t = new Toyota();
console.log("t.constructor: " + t.constructor);
console.log(t.type);
};
The output in the Firefox console looked like this:
Toyota.prototype.constructor: function () {
var self = this;
self.type = "Toyota";
self.go = function () {
console.log("A Toyota car is going...");
};
}
Original called
t.constructor: function () {
var self = this;
self.type = "Toyota";
self.go = function () {
console.log("A Toyota car is going...");
};
}
Car
As seen from the output, the new Toyota() call:
var t = new Toyota();
did not run the Toyota.prototype.constructor function as expected, instead it still used the original function definition:
Toyota = function() { console.log("Original called"); };
A highly upvoted post provided detailed explanations and examples. It mentioned "3. It executes the constructor function, using the new object whenever this is mentioned." Does the term "constructor" refer to prototype.constructor? How are the following 3 lines related:
- Toyota = function() { console.log("Original called"); }
- Toyota.prototype.constructor = function() { ...
- var t = new Toyota();
[EDIT] My biggest confusion lies in why the constructor (Toyota.prototype.constructor) is not triggered when I invoke new Toyota()?