why does listing the actual constructor of a class in javascript important

感情迁移 提交于 2019-12-03 03:08:46

Every function has a prototype property, it's assigned when the function object is created, it points to a newly created object that inherits from Object.prototype, and it has a constructor property, that simply points back to the function itself.

The purpose of the prototype property is to give a way to implement inheritance, using constructor functions. When you call a function with the new operator, it will create a new object that inherits from that constructor's prototype.

Now, the purpose of the constructor property is to have a way to refer back to the constructor that has created an object, for example:

function Foo () {}
// default value of the property:
Foo.prototype.constructor == Foo; // true

This property is inherited by the "instances" of Foo, so you can know which constructor was used to create an object:

var foo = new Foo();
foo.constructor == Foo;

If you assign a new object to the function's prototype, this relationship is lost:

function Bar () {}
Bar.prototype = { inherited: 1 };

Bar.prototype.constructor == Bar;    // false
Bar.prototype.constructor == Object; // true

And it affects also the instances of the function:

var bar = new Bar();
bar.constructor == Bar;    // false
bar.constructor == Object; // true

Another similar case is when you have two or more levels of inheritance using constructors, the most common way is used to denote the inheritance relationship between the functions, is to assign the prototype property of the second level, e.g.:

function Parent() {}

function Child () {}
Child.prototype = new Parent();

The above code has several problems, first, it executes the logic of the parent constructor to create the inheritance relationship, but that's another story, in the above example the constructor property is also affected, since we replace completely the Child.prototype object:

var child = new Child();
child.constructor == Parent; // true

If we replace replace the value of the constructor property of Child.prototype after assigning it, it will show the expected behavior:

function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child = new Child();
child.constructor == Child; // true

I believe this has to do with instantiating Bar with the new keyword. I believe using new will look for Bar.prototype.constructor. Before that line the object linked to Bar.prototype.contructor is of type Foo so when instantiated without that line it will make a Foo object instead of a Bar object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!