Reputation: 37038
I have the following code:
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;
}
}
})
}
and following code to execute:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
this output the newName OldSurname
if to change it a bit:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
console.log(vasya.lastName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
it returns oldName newSurname
Please explain why now I see oldName
insted of newName
Upvotes: 2
Views: 343
Reputation: 814
You have to use "this" keyword when you reference fullNameValue or it will use the var that you passed as param
function User(fullName) {
this.fullName = fullName;
Object.defineProperties(this,
{
firstName: {
get: function () {
return this.fullName.split(" ")[0];
}
,
set: function (fName) {
this.fullName = fName + " " + this.lastName;
}
},
lastName: {
get: function () {
return this.fullName.split(" ")[1];
}
,
set: function (lName) {
this.fullName = this.firstName + " " + lName;
}
}
})
}
Upvotes: 1
Reputation: 37038
I played with this code and found out that it was naming conflict. this variant works properly
function User(fullNameValue) {
this.fullName = fullNameValue; // renamed function argument
Object.defineProperties(this,
{
firstName: {
get: function () {
return this.fullName.split(" ")[0];//I use this here. without it I returned function argument
}
,
set: function (fName) {
this.fullName = fName + " " + this.lastName;
}
},
lastName: {
get: function () {
return this.fullName.split(" ")[1];//I use this here. without it I
}
,
set: function (lName) {
this.fullName = this.firstName + " " + lName;
}
}
})
}
Upvotes: 1