4

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?

1
  • This question is similar to: What does (…).prototype.constructor do?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jan 22 at 15:39

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, every post, book, about javascript inheritance, tells us to fix the prototype constructor, after that situtation: A.prototype = Object.create(B.prototype); A.prototype.constructor = B //fixing here I undestand what Object.create does, however the next line seems to be useless. I wrote some code removing it and that has no effect. So my question is, why everybody says to fix the constructor ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.