What is passing by value?
In other words, copying the value outside the function to the parameter inside the function is the same as copying the value from one variable to another variable.
Pass by value
A simple example:
##
var value = 1; function foo(v) { v = 2; console.log(v); //2 } foo(value); console.log(value) // 1
Passing by reference
Although copying is easy to understand, when the value is a complex data structure, copying will cause performance problems. So there is another way of passing called passing by reference. The so-called passing by reference means passing the reference of the object. Any changes to the parameters inside the function will affect the value of the object, because both refer to the same object. For example:var obj = { value: 1 }; function foo(o) { o.value = 2; console.log(o.value); //2 } foo(obj); console.log(obj.value) // 2
Is this passing by reference?
The third delivery method
Don’t worry, let’s look at another example:var obj = { value: 1 }; function foo(o) { o = 2; console.log(o); //2 } foo(obj); console.log(obj.value) // 1
Note: Passing by reference is passing a reference to the object, while passing by sharing is passing a copy of the reference of the object!
So if you modify o.value, you can find the original value through reference, but modifying o directly will not modify the original value. So the second and third examples are actually passed by sharing. Finally, you can understand it this way: If the parameter is a basic type, it is passed by value, if it is a reference type, it is passed by sharing. But because the copy is also a copy of the value, it is also directly considered to be passed by value in the elevation.The above is the detailed content of Detailed explanation of JavaScript parameter passing by value and reference passing usage examples. For more information, please follow other related articles on the PHP Chinese website!