更改原型后,Javascript对象丢失了构造函数 [英] Javascript object lost constructor when the prototype was changed
问题描述
在下面的代码中
var A = function() {};
var a = new A();
var b = new A();
A.prototype = {};
var c = new A();
console.log(a.constructor === b.constructor);
console.log(a.constructor === c.constructor);
输出为 true
和 false
.
我对错误的输出感兴趣. a
和 c
是使用相同构造函数(即 A
)创建的-为什么它们的构造函数属性不同?看来我很想念东西.
I am interested in the false output. a
and c
were created using same constructor function which is A
- why is their constructor property different? It seems I miss something.
PS.如果我删除要更改A输出原型的行,则为: true true
.
PS. If I remove the line where I am changing prototype of A output is: true true
.
推荐答案
构造对象时,构造函数的 prototype
属性被复制到新对象的__proto __
,因此,虽然 a
和 b
保留了旧的原型(还包含 .constructor
属性),但 c
使用新的空白原型(没有 constructor
作为自己的属性).这是一个图:
When you construct an object, the constructor's prototype
property is copied to the new object's __proto__
, so while a
and b
retain the old prototype (which also contains the .constructor
property), c
uses the new blank prototype (which doesn't have constructor
as own property). Here's a diagram:
在 a之后=新的A;b =新A
:
在 A.prototype = {}之后;c =新的A()
如您所见,直接分配给原型会破坏JS对象系统,并可能导致令人惊讶的结果(您的问题就说明了这一点).这就是为什么它通常不被接受的原因.
As you can see, direct assignment to a prototype breaks the JS object system and may lead to surprising results (which your very question demonstrates). That's why it's generally frowned upon.
这篇关于更改原型后,Javascript对象丢失了构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!