对 javascript 的构造函数和原型感到困惑吗?
function MyObject(){}
Array.prototype={};
MyObject.prototype={};
var a=new Array();
var b=new MyObject();
alert(a.constructor==Array);//true
alert(b.constructor==MyObject);//false
function MyObject(){}
Array.prototype={};
MyObject.prototype={};
var a=new Array();
var b=new MyObject();
alert(a.constructor==Array);//true
alert(b.constructor==MyObject);//false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Array.prototype
是一个不可写的属性。因此,您的分配:
...未成功,因此其
.constructor
属性未更改。15.4.3.1 Array.prototype
...而使用自定义构造函数,您可以分配不同的原型对象,因此您已经覆盖了通过
.constructor
引用构造函数的原始对象。Array.prototype
is a non-writable property.As such, your assignment:
...doesn't succeed, and so its
.constructor
property hasn't changed.15.4.3.1 Array.prototype
...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
.当您使用自己的空对象实例覆盖
prototype
属性时,constructor
属性将被覆盖,因为({}).constructor === Object
。你可以做或者(更好的IMO)你不能直接设置
prototype
,而是增强它:还要注意:
Array.prototype
不可写,所以你的行< code>Array.prototype = {} 将默默地失败(或在严格模式下大声失败)。The
constructor
property is overwritten when you override theprototype
property with your own empty object instance, since({}).constructor === Object
. You can do eitheror (better IMO) you can not set
prototype
directly, but instead augment it:Also of note:
Array.prototype
is not writable, so your lineArray.prototype = {}
will silently fail (or noisily fail in strict mode).您无法为 Array.prototype 赋值。
Array.prototype 有一个引用 Array 函数的构造函数属性。由于 a 是 Array 的实例,因此它继承了 Array.prototype 的构造函数属性。
您已将一个空对象分配给 MyObject.prototype,它没有 prototype 属性,b 也没有。
You can't assign a value to Array.prototype.
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.
You have assigned an empty object to MyObject.prototype, it does not have a prototype property, nor does b.