为什么这个 Javascript 示例复制变量值而不是通过引用传递?
在 Javascript The Good Parts 中,它指出:
所以我期望以下代码示例输出1001,因为“对象永远不会被复制,而是通过引用传递”,那么为什么它会输出0000?
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';
$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"
添加:
@Gareth @David,谢谢,这就是我试图在这个例子中展示的内容,有效:
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';
$('p#test').html(page_item.access_groups.developer); //is '1001'
In Javascript The Good Parts, it states:
So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';
$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"
Added:
@Gareth @David, thanks, this is what I was trying to show in this example, works:
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';
$('p#test').html(page_item.access_groups.developer); //is '1001'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要考虑 C++ 上下文中的引用传递,因为它不一样。
如果字符串上有一个方法可以改变它们,那么这个:
将改变
page_item.access_groups.member
。但是,使用=
您正在更改变量的引用,而不是它之前引用的对象Don't think of pass-by-reference in the C++ context, because it's not the same.
If there was a method on strings which changed them, then this:
would alter
page_item.access_groups.member
. However, with your=
you are changing the variable's reference, not the object it previously referenced因为
page_item.access_groups.member
是一个字符串而不是一个对象。Because
page_item.access_groups.member
is a string and not an Object.这可能会受到 JS-Gurus 的攻击,但基本上它是这样的:
对象是通过引用传递的。
字符串(数字等......基本上是一维变量)按值传递。
我确实尝试并理解了关于数据类型的冗长解释,但我确实需要完成一些工作,但没有时间更仔细地研究它。
This is probably getting bashed by JS-Gurus but basically it goes down like this:
Objects are passed by reference.
Strings (numbers, etc... basically 1 dimensional variables) are passed by value.
I did try and understand the lengthy explanations on data types but I seriously needed some work done and haven't gotten time to look at it more closely.