在全局对象值上的函数中的对象分配的影响
有人可以帮助解释为什么OBJ1的价值属性在OBJ2中变化时保持不变?我知道这与在更改功能中分配给OBJ2的OBJ1有关,但我不确定为什么。谢谢!
let obj1 = {
value: "a"
}
let obj2 = {
value: "b"
}
function change(obj1, obj2) {
obj1 = obj2
obj1.value = "c"
}
change(obj1, obj2);
console.log("obj1: ", obj1, "obj2: ",obj2);
Can someone please help explain why the value property of obj1 remains the same while in obj2 it changes? I know it has to do with obj1 being assigned to obj2 within the change function but I'm not exactly sure why. Thanks!
let obj1 = {
value: "a"
}
let obj2 = {
value: "b"
}
function change(obj1, obj2) {
obj1 = obj2
obj1.value = "c"
}
change(obj1, obj2);
console.log("obj1: ", obj1, "obj2: ",obj2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们重命名一些变量,以便您可以看到现在正在发生的事情
,
obj1
永远不会更改。您要更改的是更改
函数的参数,该函数与外部范围的变量相同。Let's rename some variables so you can see what's going on
Now as you can see,
obj1
is never changed. What you are changing is parameter ofchange
function that is named the same as variable from outer scope.这是因为对象的变量实际上是对象的指针。这就是为什么当它们传递到函数时,指针属性的任何更改都会改变实际对象。鉴于,如果您简单地将一个值分配给类型对象的变量,则指针本身会更改,而不是对象。
因此,
obj1 = obj2
将OBJ1指针设置为OBJ2指针。现在,如果obj1.value =“ c”
,则对象OBJ1(现在是OBJ2)的属性将会改变,从而影响原始对象。This is because variables of objects are actually pointers to the object. That's why when they are passed to a function, any changes of the pointer properties would change the actual object. Whereas, if you simply assign a value to a variable of type object, then the pointer itself is changed, not the object.
So
obj1 = obj2
sets the obj1 pointer to be obj2 pointer. Now, ifobj1.value = "c"
then a property of the object obj1 (which is now obj2) will change, affecting the original object.