Why has the constructor changed?

Why does the constructor change from Foo to Object after adding a prototype? How to access the original constructor?

code:

function Foo() {} var foo1 = new Foo(); console.log('foo1: ' + foo1.constructor); Foo.prototype = {} var foo2 = new Foo(); console.log('foo2: ' + foo2.constructor); 

Output:

 foo1: function Foo() {} foo2: function Object() { [native code] } 

http://jsfiddle.net/vDCTJ/

+4
source share
2 answers

This is because you gave Foo a new object for your prototype, and you did not set the constructor property of this object.

 Foo.prototype = { constructor: Foo }; 

Objects with given objects receive an object for their "prototype" property, which is already initialized in this way.

+7
source

You can not.

foo1 was created with the original Foo.prototype object, which has a constructor reference to Foo , which it inherits.

In contrast, foo2 inherits from the empty object that you set Foo.prototype before creating it. And this object inherits its constructor property from Object.prototype , so foo2.constructor === Object .

+1
source

Source: https://habr.com/ru/post/1483488/


All Articles