如何在 "double assignment" 中引用值
How are values referenced in a "double assignment"
我很好奇,所以我试了一下:
var test = example = 5;
现在,这是一种比较常见的定义事物的方式...
(例如在节点中,module.exports = exports = ...
)
以上相当于:
example = 5;
var test = example;
现在,如果变量实际上不保存值,而是对内存中值的引用,当我更改 example
时,如果 test
引用 example
正在引用一个值,test
不应该也有与 example
相同的值吗?让我们试试吧:
var test = example = 5;
example = 7;
console.log(test, example);
...现在,由于我上面所说的,输出并不是我所期望的。你明白了:
5 7
但是如果 test
引用 example
,而 example
现在是 7
,test
怎么还是 5
?他们不应该都是7
吗?
EDIT
尝试使用对象代替...但我得到了相同的行为:
var test = example = {"hello":"world", "foo":"bar"};
example = {"test":"example"};
console.log(test, example);
这输出:
Object {hello: "world", foo: "bar"}
Object {test: "example"}
所以,它们仍然和我预期的不一样。
var a = {}; // There is one object in memory
var b = a; // now both `b` and `a` refer to that object
a = {}; // now we create another object and put a reference to it to an `a`
// we haven't changed `b` so it refers to the former object
总结一下:在 JS 中你不能改变另一个变量的值。上例中变量 a
和 b
的值是一个 引用 ,而不是对象本身。更改变量值的唯一方法是重新为其分配另一个值。所以你不能在 JS 中间接改变一个变量的值,完全 (?).
当谈到 java 脚本时,变量可以接受相乘的值。 JavaScript 是一种非常 'forgiving' 的语言,让我们这样称呼它吧。
因此,如果您说例如:
var test = example = 5;
test 仍然是 5,因为 test 现在的值是 5。在这种情况下,test 只是对 example 的引用。
示例的实际值为 7。
example = 7;
所以是的,这有点奇怪,但是 javascript 的行为与其他编程语言有点不同。
我很好奇,所以我试了一下:
var test = example = 5;
现在,这是一种比较常见的定义事物的方式...
(例如在节点中,module.exports = exports = ...
)
以上相当于:
example = 5;
var test = example;
现在,如果变量实际上不保存值,而是对内存中值的引用,当我更改 example
时,如果 test
引用 example
正在引用一个值,test
不应该也有与 example
相同的值吗?让我们试试吧:
var test = example = 5;
example = 7;
console.log(test, example);
...现在,由于我上面所说的,输出并不是我所期望的。你明白了:
5 7
但是如果 test
引用 example
,而 example
现在是 7
,test
怎么还是 5
?他们不应该都是7
吗?
EDIT
尝试使用对象代替...但我得到了相同的行为:
var test = example = {"hello":"world", "foo":"bar"};
example = {"test":"example"};
console.log(test, example);
这输出:
Object {hello: "world", foo: "bar"}
Object {test: "example"}
所以,它们仍然和我预期的不一样。
var a = {}; // There is one object in memory
var b = a; // now both `b` and `a` refer to that object
a = {}; // now we create another object and put a reference to it to an `a`
// we haven't changed `b` so it refers to the former object
总结一下:在 JS 中你不能改变另一个变量的值。上例中变量 a
和 b
的值是一个 引用 ,而不是对象本身。更改变量值的唯一方法是重新为其分配另一个值。所以你不能在 JS 中间接改变一个变量的值,完全 (?).
当谈到 java 脚本时,变量可以接受相乘的值。 JavaScript 是一种非常 'forgiving' 的语言,让我们这样称呼它吧。
因此,如果您说例如:
var test = example = 5;
test 仍然是 5,因为 test 现在的值是 5。在这种情况下,test 只是对 example 的引用。
示例的实际值为 7。
example = 7;
所以是的,这有点奇怪,但是 javascript 的行为与其他编程语言有点不同。