简体   繁体   English

JavaScript中的按值传递和按引用传递有什么区别?

[英]What's the difference between pass-by-value and pass-by-reference in JavaScript?

Let's consider this: 让我们考虑一下:

 var obj = {a: 'tony'}; someFn(obj); 

and this: 和这个:

 someFn({a: 'tony'}); 

Since we know that 'obj' is a reference, "{a: 'tony'}" is an object literal, is there any difference between those two ways of passing an argument? 既然我们知道'obj'是一个引用,“ {a:'tony'}”是一个对象常量,那么这两种传递参数的方式之间有什么区别吗?

What's the difference between pass-by-value and pass-by-reference in JavaScript? JavaScript中的按值传递和按引用传递有什么区别?

That there is no pass-by-reference in JavaScript, only pass-by-value. JavaScript中没有按引用传递,只有按值传递。

Since we know that 'obj' is a reference… 因为我们知道'obj'是一个引用...

No, obj is a variable. 不, obj是变量。 And there are no references to variables that can be passed around. 而且没有对可以传递的变量的引用。 You always pass the value of the variable in a call like someFn(obj) . 您总是在诸如someFn(obj)的调用中传递变量的值。

However, the variable might hold an object reference as its value, and that is indeed the value that is passed here. 但是,变量可能对象引用作为其值,而这实际上就是在此处传递的值。 Which will allow the function someFn to mutate the object in place, but not assign to the variable obj . 这将使someFn函数可以在适当位置someFn 对象 ,但不能将其分配给变量obj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM