Copy variable values
When a variable copies a base type value and a reference type value to another variable, there is a difference.
One variable copies the value of the base type to another variable, creates a new value on the variable's object, and then copies the value to the location assigned to the new variable.
var num1 = 7;var num2 = num1;
Look at the following diagram:
Two values do not affect each other
One variable assigns the value of a reference type to another variable, in effect copying a pointer to that address.
var obj1 = new Object();var obj2 = obj1;obj1.name = "jack";alert(obj2.name); //"jack"
Specific
Two values can affect each other
When a pass parameter passes a value of a primitive type to a parameter, the passed value is copied to a local variable
function add(num){ num =+ 10; return num;}var count = 20;var sum = add(count);alert(count); //20 alert(sum); //30
When a value of a reference type is passed to a parameter, the address of the value in memory is copied to a local variable, so the change of the local variable is reflected outside the function.
function setBook(obj){ obj.name = "JavaScript高级程序设计"; obj = new Object(); obj.name = "HTML基础"}var book = new Object();setBook(book);alert(book.name); //"JavaScript高级程序设计"
As you can see, the outside of the function is affected, but why not output "HTML basics"? Because objects that have been modified in the local scope are reflected in the global scope as an Ann value is passed.
In the above code, if it is passed by reference, the HTML base should be output. This means that even if the value of the parameter is modified inside the function, the original reference remains unchanged. in fact, when you override obj inside a function, the reference to that variable is a local object. This local object is destroyed immediately after the function is executed .
function setBook(obj){ obj = new Object(); obj.name = "HTML基础"}var book = new Object();setBook(book);alert(book.name); //undefined
JavaScript advanced Programming (copy variable values, pass parameters)