简体   繁体   English

对 javascript 的构造函数和原型感到困惑?

[英]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

Array.prototype is a non-writable property. Array.prototype是不可写的属性。

As such, your assignment:因此,您的任务:

Array.prototype = {}

...doesn't succeed, and so its .constructor property hasn't changed. ...没有成功,所以它的.constructor属性没有改变。

15.4.3.1 Array.prototype 15.4.3.1 Array.prototype

The initial value of Array.prototype is the Array prototype object (15.4.4). Array.prototype的初始值为 Array 原型 object (15.4.4)。

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }此属性具有属性{ [[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 . ...而使用您的自定义构造函数,您可以分配不同的原型 object,因此您已经覆盖了通过.constructor引用构造函数的原始原型。

The constructor property is overwritten when you override the prototype property with your own empty object instance, since ({}).constructor === Object .当您使用自己的空 object 实例覆盖prototype属性时, constructor属性将被覆盖,因为({}).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:或者(更好的 IMO)你不能直接设置prototype ,而是增加它:

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).另请注意: Array.prototype不可写,因此您的行Array.prototype = {}将静默失败(或在严格模式下大声失败)。

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

You can't assign a value to Array.prototype.你不能给 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. Array.prototype有一个构造函数属性,它引用了数组function。 Since a is an instance of Array , it inherits Array.prototype 's constructor property.由于 a 是Array的一个实例,它继承了Array.prototype的 constructor 属性。

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

You have assigned an empty object to MyObject.prototype , it does not have a prototype property, nor does b .您已将一个空的 object 分配给MyObject.prototype ,它没有原型属性,也没有b

MyObject.prototype.constructor = MyObject;

alert(b.constructor==MyObject); // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM