新的JavaScript原型更改构造函数 [英] New JavaScript prototype changes constructor

查看:146
本文介绍了新的JavaScript原型更改构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用构造函数创建对象时,它具有指向构造函数的构造函数属性:

  var Foo = function(foo){
this.foo = foo;
}
var myFoo = new Foo(123);
myFoo.constructor === Foo; // true

创建此对象后,可以更改 Foo.prototype ...

  Foo.prototype.x ='y'; 

...或重新分配一个新的原型对象:

  Foo.prototype = {
num:99
};
myFoo.constructor === Foo; // still tr​​ue

但是如果我在之后创建一个新的Foo对象<一个新对象 Foo.prototype 其构造函数突然指向 Object

  var myBar = new Foo(321); 
myBar.constructor === Foo; // false
myBar.constructor === Object; // wtf ?!

添加新的属性到原型不会产生这种效果,你必须做< c $ c> Foo.prototype = {...}



我不知道为什么创建一个新的原型会影响构造函数属性。我在Chrome,Firefox和Internet Explorer中测试,所有结果相同。

解决方案

任何人的构造函数对象从该对象的原型继承。



使用任何函数创建的默认原型对象包含构造函数引用该函数的属性,如规范



您的新原型对象没有构造函数属性,而是具有从 Object.prototype 继承的构造函数属性。


When you create an object with a constructor it has a constructor property pointing to the constructor function:

var Foo = function(foo) {
    this.foo = foo;
}
var myFoo = new Foo(123);
myFoo.constructor === Foo; // true

After creating this object I can change Foo.prototype ...

Foo.prototype.x = 'y';

... or reassign a new prototype object:

Foo.prototype = {
    num: 99
};
myFoo.constructor === Foo; // still true

But if I create a new Foo object after assigning a new object to Foo.prototype its constructor suddenly points to Object:

var myBar = new Foo(321);
myBar.constructor === Foo; // false
myBar.constructor === Object; // wtf?!

Adding new properties to the prototype doesn't produce this effect, you have to do the assignment Foo.prototype = {...}.

I have no idea why creating a new prototype would affect the constructor property. I tested in Chrome, Firefox and Internet Explorer, all with the same result. Can anybody help me understand this?

解决方案

The constructor property of any object is inherited from that object's prototype.

The default prototype object created with any function contains a constructor property that refers to that function, as detailed in the spec.

Your new prototype object doesn't have that constructor property, and instead has its own constructor property inherited from Object.prototype.

这篇关于新的JavaScript原型更改构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆