在javascript中的范围表现怪异 [英] Scope in javascript acting weird

查看:88
本文介绍了在javascript中的范围表现怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象在javascript中传递给它们的引用。该物体的意义从任何地方应该反映出来。
在这种情况下,console.log(a)的预期输出是{} {/ b>

Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(a)

function change(a,b) {
    a.x = 'added';
    a = b;//assigning a as {} to b
}
a={}
b={}
change(a,b);
console.log(a); //expected {} but output {x:'added'}
console.log(b)

这里发生了什么?据我所知,这不应该是因为功能范围。
谢谢

What is happening here? It should not be because of functional scope as far as I know. Thank you

推荐答案

如果您添加了另一行,您可以更清楚地了解正在发生的事情:

If you added another line you can get a clearer picture of what is happening:

function change(a,b) {
    a.x = 'added';
    a = b;
    a.x = 'added as well';
};
a={};
b={};
change(a,b);
console.log(a);  //{x:'added'}
console.log(b);  //{x:'added as well'}

当你在做 a = b 您将局部变量 a 分配给 b 持有。

When you're doing a = b you're assigning the local variable a to the reference that b is holding.

这篇关于在javascript中的范围表现怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆