+ 2
Value vs Reference
function changeAgeAndReference(person) { person.age = 25; person = { name: 'John', age: 50 }; return person; } var personObj1 = { name: 'Alex', age: 30 }; var personObj2 = changeAgeAndReference(personObj1); console.log(personObj1); // -> { name: 'Alex', age: 25 } console.log(personObj2); // -> { name: 'John', age: 50 } why doesn't person(John, 50) in the first function overwrite person in the centre(Alex, 30)
7 Antworten
+ 1
Because although you send Alex/30, you override that inside the function to John/50... I am wonderibg how you get Alex/25 when you don't call that function...
+ 1
person is a parameter that first refers to person1, but then you change the reference to person2, but this only affects the parameter not the object
+ 1
IZzZI sorry didn't mean personObj2, I meant the reference changes to another person object throughout the function. That is, when the first line (person.x = 25) is executed, person does indeed refer to personObj1, but in the next line the parameter 'person' is given a new object. We lose our *reference* to personObj1 and start modifying a new entity, which is then returned.
0
Jiří Bočan Can you elaborate your answer please. Thank You. Btw the function is called when
var personObj2 = changeAgeAndReference(personObj1);
0
Check this:
function changeAgeAndReference(person) {
person.age = 25;
person = {
name: 'John',
age: 50
};
return person;
}
var personObj1 = {
name: 'Alex',
age: 30
};
console.log(personObj1); // -> { name: 'Alex', age: 30 }
var personObj2 = changeAgeAndReference(personObj1);
console.log(personObj1); // -> { name: 'Alex', age: 25 }
console.log(personObj2); // -> { name: 'John', age: 50 }
`
-------
The first console.log() shows you the original personObj1 (Alex/30).
The second console.log() gives Alex/25 because you change the age value of "person" = "personObj1", which is a function argument, by assigning "person.age = 25;".
And then, regardless of what the "person" argument is like, you override/redefine the "person" object completely - you override both name and age by
person = {
name: 'John',
age: 50
};
(this is what changeAgeAndReference() returns: John/50).
0
I understand everything except this. After the function is called person = personObj1 right?
var personObj1 = {
name: 'Alex',
age: 30
};
person = { // person = personObj1
name: 'John',
age: 50
};
Since both objects are referring to personObj1, shouldn't the second object override the first one?
0
Dan Walker when did i change my reference to personObj2?