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

六月ゝ 毕业季﹏ 提交于 2019-12-02 10:04:07

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).

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.

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