JavaScript & Constructor

What is constructor?

ECMAScript is a object based language. An object has a built-in property named constructor.

The constructor will reference the function which made the object.

function Foo();

var foo = new Foo();

foo.constructor === Foo; // true

How is constructor created?

When you created the foo object:


var foo = new Foo();

JavaScript engine creates a new functon object from your declaration. Togther with this, your prototype is created as well.

This default value the prototype is an object with property constructor, which is set to the function itself.

So, when new Foo is called, the Foo.prototype becomes __proto__ and the constructor becomes accessible from the object:


function Foo() { }

var foo = new Foo();

console.log(

  foo.hasOwnProperty('constructor'), // false
  Foo.constructor === Function, // true
  Foo.prototype.hasOwnProperty('constructor') // true

);

Prototype & the constructor

If we replace the prorotype, we will end up losing the constructor:


function Foo() { }

var foo = new Foo();

foo.constructor === Object; // false
foo.constructor === Foo; // true

Foo.prototype = {};

foo = new Foo();

foo.constructor === Object; // true

What happens here is: when we created the foo object, the JavaScript engine creates an object and sets its constructor to Foo.

But we overrode the prototype of the Foo with {}. This object ({}), does not have a constructor, so the compiler falls back to its __proto__, using the native Object.prototype.constructor.

Preserving constructor

Additional code is usually required to prevent it from being overwritten. If you intent to keep it correct, then put it into the new prototype, like this:

function Foo() { }

Foo.prototype = { };

var foo = new Foo();

foo.constructor === Foo; // false

Foo.prototype = { constructor: Foo };

foo = new Foo();

foo.constructor === Foo; // true

Be first to comment

Leave a Reply