0
Javascript object
let person = { name: 'Jack', age: 18, sex: 'male' }; let student = { name: 'Bob', age: 20, xp: '2' }; let newStudent = Object.assign({}, person, student); console.log(newStudent.name); // Bob console.log(newStudent.age); // 20 console.log(newStudent.sex); // male console.log(newStudent.xp); // 2 while console logging I am getting the result I have shown after //. How would I came up to know that newStudent.name will print Bob why not Jack . and why newStudent.age will print 20 why noyt18 ?
4 Respostas
+ 4
The syntax of Object.assign() looks like this
Object.assign(target, ...sources)
and it returns the target object.
So, in your code, the target object is {} and the sources include person object and student object. It will clone a person object and student object to the target object.
The reason why nameStudent.name show Bob because the properties are overwritten by other objects that have the same properties later in the same order of parameters.
+ 1
First person is assigned to an empty object then student is assigned to this new object. When an object is assigned it will overwrite all previous members with its own values. Therefore student overwrites persons name and age attributes. If you change the order it will be the other way around.
+ 1
Thanks guys for your help
0
Great explanation by Phurinat Puekkham