Today I have a question to share with you in the wechat group:
Attached source code:
function changeAgeAndReference(person){
person . age = 25;
person = {
nage : 'John',
age : 50
};
return person ;
}
var personObj1={
name : 'Alex',
age : 30
}
var personObj2 = changeAgeAndReference(personObj1);
console.log(personObj1)
console.log(personObj2)
Copy the code
What does it output? The answer is:
{name: "Alex", age: 25}
{nage: "John", age: 50}
Copy the code
To understand why the answers are 25 and 50 to understand the Js variable assignment problem:
1. Js has two types of data: value type (base type) and reference type
Value types (basic types) : String, Number, Boolean, Null, Undefined, Symbol Reference data types: Object, Array, Function.
Basic data types are accessed by value because you can manipulate the actual values stored in variables; The value of a reference type is an object held in memory, and when you manipulate an object, you are actually manipulating the reference to the object rather than the actual object
2. Copy variables
Basic type replication: for example
var num1 = 5;
var num2 = num1;
Copy the code
The value saved in num1 is 5. When num2 is initialized with the value of num1, num2 also stores the value 5. But the 5 in num2 is completely separate from the 5 in num1, and the value is just a copy of the 5 in num1. Thereafter, the two variables can participate in any operation without affecting each other
Reference type replication: For example
var obj1 = new Object();
var obj2 = obj1;
obj1.name = "Nicholas";
alert(obj2.name);
Copy the code
The variable obj1 holds a new instance of an object. This value is then copied into obj2; In other words, obj1 and obj2 both point to the same object. This way, when you add the name attribute to obj1, you can access it through obj2, since both variables reference the same object
Now let’s get back to the problem
function changeAgeAndReference(person){
person . age = 25;
person = {
nage : 'John',
age : 50
};
return person ;
}
var personObj1={
name : 'Alex',
age : 30
}
var personObj2 = changeAgeAndReference(personObj1);
console.log(personObj1)
console.log(personObj1)
Copy the code
Var personObj2 = changeAgeAndReference(personObj1)
var person = personObj1
Copy the code
PersonObj1 and Person both refer to the same object. Changing the age attribute of Person changes the age of personObj1. So personObj1 becomes {name: “Alex”, age: 25}
Inside the function:
person = {
nage : 'John', age : 50 }; Var person = {nage:'John',
age : 50
};
Copy the code
Person is reassigned and no longer refers to the previous object, so return {nage: “John”, age: 50}
Article Reference:
“JavaScript advanced Programming” Chinese version of the third edition