Confused by javascript's constructor and prototype?
function 开发者_JAVA百科MyObject(){}
Array.prototype={};
MyObject.prototype={};
var a=new Array();
var b=new MyObject();
alert(a.constructor==Array);//true
alert(b.constructor==MyObject);//false
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
.
The constructor
property is overwritten when you override the prototype
property with your own empty object instance, since ({}).constructor === Object
. You can do either
function MyObject() {}
MyObject.prototype = {};
MyObject.prototype.constructor = MyObject;
or (better IMO) you can not set prototype
directly, but instead augment it:
function MyObject() {}
MyObject.prototype.foo = "bar";
Also of note: Array.prototype
is not writable, so your line Array.prototype = {}
will silently fail (or noisily fail in strict mode).
> function MyObject(){}
> Array.prototype={};
You can't 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 Array.prototype's constructor property.
> alert(b.constructor==MyObject);//false
You have assigned an empty object to MyObject.prototype, it does not have a prototype property, nor does b.
MyObject.prototype.constructor = MyObject;
alert(b.constructor==MyObject); // true
精彩评论