David Hellsing
David Hellsing

Reputation: 108520

JavaScript constructors

I'm trying to get a grip of javascript constructors and if they are really read-only. Here is a simple test scenario:

var A = function(){}

console.log( A.prototype.constructor == A ); //true

So at this point, every new function receives a prototype object that contains the constructor as a reference. That's all good. Now consider this:

var B = function() {
    this.id = 0;
}

A.prototype.constructor = B; // what does this do with A?

So now, every instance of A should get B as constructor:

var C = new A();

console.log(C.constructor == B) // true

So finally, does this have any real effect on each instance? It doesn't seem so:

console.log(C.id); // what will this yield?

My question is: what is the purpose of exposing a constructor reference? Apparently you can set/override it, but it doesn't do anything except changing the reference. Or am I missing something?

Upvotes: 4

Views: 530

Answers (1)

casablanca
casablanca

Reputation: 70731

The constructor property is just for convenience, it has absolutely no effect on how your program behaves. By default, when you define a function, func.prototype.constructor is set to func itself -- you can set it to whatever you want later and it makes no difference. The object that is constructed depends solely on the function that you pass to new: if you do new A(), it will always call function A.

Upvotes: 5

Related Questions