Are variables/objects passed by value and why can't I change object's property with variable in javascript?
本问题已经有最佳答案,请猛点这里访问。
假设我有一个对象:
1 2 3 4 | var obj = { len: 4, bred: 5 } |
现在假设我将这个对象分配给一个变量
1 | x.len = 99 |
然后,
1 2 3 | var r = 2, s = 3, t = 4; s = r; s = 88; |
现在,
问题1:如果变量(包括对象)在javascript中按值传递,那么为什么更改
另一个问题是,当分配给变量时,我不能更改对象的属性。考虑这种情况:
1 2 3 4 5 6 | var obj2 = { len: 4, bred: 5 } var x2; x2 = obj.len; |
现在在控制台中键入
问题2:为什么我不能用变量更改对象的属性?
所有东西都是按值传递的,但是当您创建一个对象时,会得到对该对象的引用。
1 2 3 4 5 6 7 | // Create an object. Assign a reference to that object to `obj` var obj = { len: 4, bred: 5 }; // Copy the value of `obj` to `x`. Now `x` is also a reference to that object. var x = obj; |
对
1 2 3 4 5 6 | var obj2 = { len: 4, bred: 5 } var x2; x2 = obj.len; |
基元类型(字符串、数字、布尔值、空值、未定义和符号)通过值传递,而对象则通过引用传递。
As far as I understand it, it creates a copy of obj and assign that copy to x -- that is pass by value.
不,
另一方面,