This seems to be something that have been discussed by many. But unfortunately, I couldn’t find an answer to my issue.
Here is a piece of code on Javascript 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);
};
And the output in Firefox console:
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
From the output, it is shown that the new Toyota() call:
var t = new Toyota();
didn’t invoke the Toyota.prototype.constructor function as expected, instead it still call the function defined in the first place:
Toyota = function() { console.log("Original called"); };
A post with high upvote count gave a fairly detailed explanation together with examples: it said “3. It executes the constructor function, using the new object whenever this is mentioned.” Does the “constructor” mentioned 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] What confuses me most is why the constructor (Toyota.prototype.constructor) is not invoked when I call new Toyota()?
The
constructorproperty inprototypeobject contains a reference to the function that constructs instances of that type of object. Hope I’m not trying to confuse here.For a string object you would see the
constructorproperty referencing theStringfunction (a.k.a constructor informally.)which is why typically we would reassign the class (i.e., the function)
constructorproperty to its own.Hope that answers your question.