Check out this code snippet:
function User(fullName) {
this.fullName = fullName;
Object.defineProperties(this,
{
firstName: {
get: function () {
return fullName.split(" ")[0];
}
,
set: function (fName) {
this.fullName = fName + " " + this.lastName;
}
},
lastName: {
get: function () {
return fullName.split(" ")[1];
}
,
set: function (lName) {
this.fullName = this.firstName + " " + lName;
}
}
})
}
Let's execute the following code as well:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
The output should be newName OldSurname
If you modify the code slightly like this:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
console.log(vasya.lastName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
You might see oldName newSurname
Can you figure out why you are getting oldName
instead of newName
?