Jiaji Wu
Jiaji Wu

Reputation: 469

What is the connection between"new" and "prototype.constructor" in Javascript?

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:

  1. Toyota = function() { console.log("Original called"); }
  2. Toyota.prototype.constructor = function() { ...
  3. var t = new Toyota();

[EDIT] What confuses me most is why the constructor (Toyota.prototype.constructor) is not invoked when I call new Toyota()?

Upvotes: 1

Views: 144

Answers (1)

g13n
g13n

Reputation: 3246

The constructor property in prototype object 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 constructor property referencing the String function (a.k.a constructor informally.)

console.log("".constructor); // would print function String() { [native code] }

which is why typically we would reassign the class (i.e., the function) constructor property to its own.

Toyota.prototype.constructor = Toyota;

var t = new Toyota();
console.log(t.constructor); // prints function Toyota() { /* definition */ }

Hope that answers your question.

Upvotes: 2

Related Questions