我想了解以下
var obj1 = {
value: "first value"
};
var obj2 = {
value: "second value"
};
var obj3 = obj2;
function change(obj1, obj2) {
obj1.value = "asdasd";
obj2 = "lol";
}
change(obj1, obj2);
console.log("1",obj1.value);//"asdasd"
console.log("2",obj2.value);//"secondvalue"
为什么只改变obj1.value ??
答案 0 :(得分:0)
当您将参数obj2更改为指向字符串时,您将丢失对传递给它的对象的引用。
function change(obj1, obj2) {
obj1.value = "asdasd";
// You are only changing the parameter obj2 not a sub property of the object it contained.
obj2 = "lol";
}