Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by javascript's 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
like image 332
simon xu Avatar asked Jul 19 '11 03:07

simon xu


1 Answers

Array.prototype is a non-writable property.

As such, your assignment:

Array.prototype = {}

...doesn't succeed, and so its .constructor property hasn't changed.

15.4.3.1 Array.prototype

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

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

...whereas with your custom constructor, you have the ability to assign a different prototype object, so you've overwritten the original which had reference to the constructor via .constructor.

like image 195
user113716 Avatar answered Sep 28 '22 20:09

user113716