javascript是通过引用还是按值处理对象? [英] Does javascript handle objects by reference or by value?
本文介绍了javascript是通过引用还是按值处理对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码
var myObjects = {}; //global variable
//Later on in the code:
for (i in myObjects)
{
var obj = myObjects[i];
process(obj);
}
function process(obj)
{
$.getJSON("example.com/process/", {id: obj.id}, function(result)
{
//Will the following change the permanent/global copy e.g
// myObjects[44] ?
obj.addItem(result.id, result.name, result.number);
}
);
}
以下行:
obj.addItem(result.id, result.name, result.number);
按值或按引用修改对象,即是否会修改<$ c $的本地副本c> obj 或者例如 myObjects [44]
?
modify the object by value or by reference, i.e will it modify the local copy of obj
or e.g myObjects[44]
?
如果只影响本地副本,如何更改对象的全局副本?
If it affects only the local copy, how can I have it change the global copy of the object?
推荐答案
原始变量在JavaScript中按值传递,但是对象通过引用传递。
Primitive variables are passed by value in JavaScript, but objects are passed by reference.
来源和进一步阅读:
- < a href =http://snook.ca/archives/javascript/javascript_pass =nofollow noreferrer> JavaScript:按值或按引用传递
- JavaScript: Passing by Value or by Reference
这篇关于javascript是通过引用还是按值处理对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文