Translator According to: wit, such as you, should be able to correct the end of the text test it? If not, please study hard, every day programming:)
Original: Explaining Value vs. Reference in Javascript
Translator: Fundebug
In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.
JavaScript has 5 basic data types: Boolean, null, Undefined, string, and number. These basic types are assigned by value in the way they are passed. It is worth noting that there are three other types: Array, function, and object, which are passed by reference. From the bottom-up technique, they are San du objects.
Basic data types
If a basic data type is bound to a variable, we can assume that the variable contains the value of the base data type.
var x = ten; var y = ' abc '; var z = null; |
When we use =
these variables to assign values to another variable, we actually copy the corresponding values and assign them to the new variable. We call it the 值传递
.
var x = ten; var y = ' abc '; var a = x; var b = y; console.log (x, Y, A, B) //Ten, ' abc ', ten, ' abc ' |
a
And x
both contain ten, b
and y
both contain ‘abc‘
, and they are completely independent copies, non-interference. If we a
change the value, it will x
not be affected.
var x = ten; var y = ' abc '; var a = x; var b = y; A = 5; b = ' def '; console.log (x, Y, A, b); //Ten, ' abc ', 5, ' Def ' |
Object
If a variable is bound to a non-basic data type (Array, Function, Object), then it records only one memory address, which holds the specific data. Note that a variable that refers to a primitive data type is equivalent to containing data, whereas a variable that now points to a non-basic data type does not itself contain data.
The object is created in memory, and when we declare it arr = []
, we create an array in memory. The arr
address of the memory is recorded.
var arr = []; //(a) Arr.push (1); //(b) |
After executing (a), an empty array object is created in memory with a memory address #001
that arr
points to that address.
variables |
Address |
Object |
Arr |
#001 |
[] |
After execution (b), there is an element in the array object, but the address of the array remains unchanged and arr
unchanged.
variables |
Address |
Object |
Arr |
#001 |
[1] |
Reference delivery
Objects are passed by reference, not by value. In other words, the variable assignment will only pass the address past.
var reference = [1]; var refcopy = reference; |
variables |
Address |
Object |
Reference |
#001 |
[1] |
Refcopy |
#001 |
reference
And refCopy
point to the same array. If we update reference
, refCopy
it will also be affected.
Reference.push (2); Console.log (reference, refcopy); //[1, 2], [1, 2] |
variables |
Address |
Object |
Reference |
#001 |
[1, 2] |
Refcopy |
#001 |
Reference re-assignment
If we re-assign a variable that has already been assigned, it will contain the new data or the reference address.
var obj = {First : ' fundebug.com '}; obj = { second: ' fundebug.cn '}; |
obj
From pointing to the first object to pointing to the second object.
variables |
Address |
Object |
Obj |
#001 |
{first: ' fundebug.com '} |
|
#002 |
{second: ' fundebug.cn '} |
If an object is not pointed to by any variable, such as the first object (address #001
), the JavaScript engine's garbage collection mechanism destroys the object and frees the memory.
= = and = = =
For a variable of a reference type, ==
and ===
only if the address of the reference is the same, it does not determine whether the property in the object or the value is the same. Therefore, if two variables point to the same object, it is returned true
.
var arrref = [' hi! ']; var arrRef2 = arrref; Console.log (arrref = = = ArrRef2); //True |
If it is a different object, it will be returned if it contains the same attributes and values in a timely manner false
.
var arr1 = ["hi!"]; var arr2 = ["hi!"]; Console.log (arr1 = = = ARR2); //False |
If you want to determine whether two different objects are really the same, an easy way is to convert them to strings and then judge them.
var arr1str = json.stringify (arr1); var arr2str = json.stringify (arr2); Console.log (arr1str = = = Arr2str); //True |
Another method is to recursively determine the value of each property until the base type is positioned and then determine whether it is the same.
function parameters
When we pass the basic type data into a function, the function assigns the copy of the data to the parameter variable of the function.
var hundred = + ; var = 2; function Multiply (x, y) {return x * y;} var twohundred = multiply (hundred, n); |
hundred
Copy the value of the value to the variable x
, which two
is copied to the variable y
.
Pure function
For a function, given an input, returns a unique output. In addition, there will be no collateral impact on the external environment. We have the opportunity to call this function a pure function. All variables defined inside the function are garbage collected after the function returns.
However, if the input to the function is an object (Array, Function, object), then a reference is passed in. The operation of the variable will affect the original object. This kind of programming will have a side effect, and the logic complexity and readability of the code is lower.
Therefore, many array functions, such as Array.map
and Array.filter
are implemented in the form of pure functions. Although their arguments are an array variable, the original array is prevented from being changed by deeply copying and assigning a new variable to it and then manipulating it on the new array.
Let's look at an example:
function changeageimpure (person) {person.age = ; return person;} var alex = {name: ' Alex ',Age: +}; var Changedalex = changeageimpure (Alex); Console.log (Alex); //{name: ' Alex ', age:25} Console.log (Changedalex); //{name: ' Alex ', age:25} |
In a non-pure function changeAgeImpure
, the object person
is age
updated and returned. The original alex
object is also affected, age
updated to 25.
Let's see how to implement a pure function:
function changeagepure (person) {var newpersonobj = Json.parse (json.stringify (person)); Newpersonobj.age = + ; return newpersonobj;} var alex = {name: ' Alex ',Age: +}; var alexchanged = changeagepure (Alex); Console.log (Alex); //{name: ' Alex ', age:30} Console.log (alexchanged); //{name: ' Alex ', age:25} |
We do this by turning the JSON.sringify
object into a string, and then by JSON.parse
changing the string back to the object. A new object is generated by this operation.
A simple face question
Value passing and reference passing are often asked in interviews to try to answer how the following code outputs:
function changeageandreference (person) {person.age = ; person = {name: ' John ',Age: +}; return person;} var personObj1 = {name: ' Alex ',Age: +}; var personObj2 = changeageandreference (personObj1); Console.log (PERSONOBJ1); //? Console.log (PERSONOBJ2); //? |
Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/08/09/explain_value_reference_in_js/
Value passing and reference passing of JavaScript