JavaScript 中令人困惑的原型行为 [英] Confusing prototype behavior in JavaScript

查看:56
本文介绍了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.bary.bar 然后表示不同的对象,而 x.fooy.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屋!

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