JavaScript 中令人困惑的原型行为 [英] Confusing prototype behavior in JavaScript
问题描述
我不明白为什么会发生以下情况:
I don't understand why the following is happening:
function Class() {}
Class.prototype.foo = {a: 1};
Class.prototype.bar = 1;
x = new Class();
y = new Class();
y.foo.a = 2;
y.bar = 2;
x.foo.a; //2
x.bar; //1
当我将 y.foo.a
设置为 2 时,它似乎在执行与 y.constructor.prototype.foo.a = 2
相同的操作.既然 y.bar = 2
不影响 y.constructor.prototype.bar
,为什么会这样?
When I set y.foo.a
to 2, it seems to be performing the same operation as y.constructor.prototype.foo.a = 2
. Why would this be, given that y.bar = 2
doesn't affect y.constructor.prototype.bar
?
推荐答案
您正在阅读 y.foo
但分配给 y.bar
.这些是具有不同语义的不同操作.设置y.foo.bar
必须先读取y.foo
:它在y
中查找foo
的值, 找不到它,然后查看 y
的原型,发现一个对象,然后才修改该对象.分配 y.bar 只是查找 y 然后修改它.x.bar
和 y.bar
然后表示不同的对象,而 x.foo
和 y.foo
表示同一个对象.
You are reading y.foo
but assigning to y.bar
. These are different operations with different semantics. Setting y.foo.bar
must first read y.foo
: it looks for the value of foo
in y
, fails to find it, then looks in y
's prototype, discovers an object, and only then modifies that object. assigning y.bar simply looks up y and then modifies it. x.bar
and y.bar
then denote different objects, while x.foo
and and y.foo
denote the same object.
这篇关于JavaScript 中令人困惑的原型行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!