Are variables/objects passed by value and why can't I change object's property with variable in javascript? [duplicate]

喜欢而已 提交于 2019-12-02 18:21:14

问题


Suppose I have an object as:

var obj = {
        len: 4,
        bred: 5
    }

Now suppose I assign this object to a variable x as var x = obj;. As far as I understand it, it creates a copy of obj and assign that copy to x — that is pass by value. Now If I change a property of x then it changes that property of the obj object too. E.g.

x.len = 99

Then both obj.len and x.len become 99. On the other hand consider this scenario:

var r = 2, s = 3, t = 4; 
s = r;
s = 88;

Now r is passed by value to s that s a copy of r was given to s. So changing s to 88 doesn't change the original value of r variable. Typing r in the console still gives 2.

Question 1: If variables (objects included) are passed by value in JavaScript then why does changing x.len change the original obj.len, too?

Another problem is that I cannot change an object's property when assigning to a variable. Consider this scenario:

var obj2 = {
        len: 4,
        bred: 5
    }
var x2;
x2 = obj.len;

Now typing x2 in console simply returns 4. But if I try to change the value of x2 such as x2 = 77; then that doesn't change obj2.len.

Question2: Why can't I change object's property with a variable?


回答1:


Everything is passed by value, but when you create an object you get an reference to that object.

// 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;

Any changes to properties of x or obj will now modify the same object because they go through copies of the same reference.


var obj2 = {
    len: 4,
    bred: 5
}
var x2;
x2 = obj.len;

len is a number, not an object, so the value isn't a reference. So when you copy it you get a copy of the number (instead of a copy of the reference to the object).




回答2:


Primitive types (strings, numbers, booleans, null, undefined and symbols) are passed by value, objects on the other hand are passed by reference.

As far as I understand it, it creates a copy of obj and assign that copy to x -- that is pass by value.

No, x is assigned a reference to the object that was first assigned to obj. It is the same object, thus it is updated both on x and obj.

obj.len on the other hand contains a primitive value, so it is copied, not referenced.



来源:https://stackoverflow.com/questions/36865168/are-variables-objects-passed-by-value-and-why-cant-i-change-objects-property-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!