Confused by the javascript constructor and prototype?

function MyObject(){} Array.prototype={}; MyObject.prototype={}; var a=new Array(); var b=new MyObject(); alert(a.constructor==Array);//true alert(b.constructor==MyObject);//false 
+6
source share
3 answers

Array.prototype is a Array.prototype -unavailable property.

So your purpose is:

 Array.prototype = {} 

... is not executed, and therefore its .constructor property .constructor not changed.

15.4.3.1 Array.prototype

The initial value of Array.prototype is an Array prototype object (15.4.4).

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }

... while with your custom constructor you have the option of assigning a different prototype object, so you rewrote the original that referenced the constructor through .constructor .

+9
source

The constructor property is overwritten when you override the prototype property with your own instance of an empty object, since ({}).constructor === Object . You can do either

 function MyObject() {} MyObject.prototype = {}; MyObject.prototype.constructor = MyObject; 

or (better IMO) you cannot install prototype directly, but instead increase it:

 function MyObject() {} MyObject.prototype.foo = "bar"; 

Also note: Array.prototype not writable, so your line Array.prototype = {} silently fails (or noisy in strict mode).

+2
source
 > function MyObject(){} > Array.prototype={}; 

You cannot assign a value to Array.prototype.

 > MyObject.prototype={}; > var a=new Array(); > var b=new MyObject(); > alert(a.constructor==Array);//true 

Array.prototype has a constructor property that references the Array function. Since a is an instance of Array, it inherits the property of the Array.prototype constructor.

 > alert(b.constructor==MyObject);//false 

You assigned an empty object MyObject.prototype, it does not have a prototype property and does not b.

 MyObject.prototype.constructor = MyObject; alert(b.constructor==MyObject); // true 
0
source

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


All Articles