Remember the truth: JS function Pass parameters, whether it is a simple data type, or reference data type, is the value of the pass!!
Here is an example of the JS Red envelope book:
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}
var person = new Object();
setName(person);
alert(person.name); // "Nicholas"
Some people will ask, since it is the value of the transfer, then I setname this function passed the person object, in the function to modify the person object, why the global person has an impact?
First, we need to be aware that this variable is the address of an object in the heap memory. So, the value passed to the function parameter ispoint to the address of the object in the heap memory,This is why the changes to this parameter inside the function are external, because they all point to the same object.
Take a look at the picture:
If it is a reference pass, the contents of the second box are passed through, there will be no fourth lattice, that is, if it is a reference pass, the person function parameter is a reference to the man variable, then the heap in memory that object has only one reference address;
The fact is that the value is passed, the parameter of the person function copies a copy of the address of the object in the heap memory, the object in the heap memory has two reference addresses, and if I modify the parameter inside the function, the object in the heap memory is actually modified;
Look at this question again:
var b = {b:1};
function addB(b){
b.b++; //
function parameter b is a pointer to the The object in the heap memory has been modified.
b={}; //
The function parameter B is pointed to another empty object, that object in heap memory is referenced only by the global B
b.b=3; //
Null object referenced by function parameter B is modified, and is destroyed when the line of code finishes executing
}
addB(b); // b变量对堆内存中对象的引用地址,被复制了一份,赋值到函数形参上
console.log(b.b);
Null
JS in the function pass parameters, whether the value of the pass or reference delivery?