3

When I was reading about prototypal inheritance in MDN, I found this code snippet.

function B(a, b){ }
B.prototype = Object.create(A.prototype, {});
B.prototype.constructor = B;
var b = new B();

For simplicity, I have removed the inner content of the functions. Here B.prototype.constructor is assigned to B, once it is created. Why this is done and what is role of prototype.constructor in the prototype chain. I found this SO question and one answer is

It's a good practice to reset a constructor after the assignment.

I would like to get a good explanation on this and what is the effect on this in the prototype chain. In MDN Object.prototype.constructor is explained as

Returns a reference to the Object function that created the instance's prototype.

I have tried out following

function A(name) {
  this.name = name
}
function B() {
  this.getName = function(){
    console.log('hello');
  }
}
var b = new B();

Here b.constructor is function A(name) and also there is another constructor available in b.__proto__.constructor and both are same. What is the difference between these two. Now when I did the following B.prototype.constructor == B, b.constructor is function B()

Now I have created a new object from b

var c = Object.create(b)

So how this is going to affect the prototype chain.

Any help is greatly appreciated. Thanks in advance.

Community
  • 1
  • 1
Vishnu Sureshkumar
  • 2,246
  • 6
  • 35
  • 52

1 Answers1

2

When you create a function, e.g.

function A() {}

automatically it receives a prototype property, which is an object with a constructor property, which is the function:

A.prototype.constructor === A;

This constructor property is not used internally by JS, so you can change it, remove it, or do what you want.

However, some codes rely on that property to get the constructor from its prototype, or from instances that inherit from that prototype. So it's better practice not to modify it.

If you replace the prototype with a new object, you are removing that constructor property. So it's better to reset it:

function A() {}
function B() {}
B.prototype.constructor; // B
B.prototype = Object.create(A.prototype);
B.prototype.constructor; // A
B.prototype.constructor = B;
B.prototype.constructor; // B
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Constructor property only enable when you initialize with new key word. – Md Atiqul Haque Jul 14 '15 at 19:14
  • @MdAtiqulHaque: Not sure what you mean. `.constructor` is not initialised with a `new` call, and if you don't call `A` with `new` then you don't create an instance obviously. – Bergi Jul 14 '15 at 20:04