我有以下代码:
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;
}
}
})
}
并执行以下代码:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
此输出 newName OldSurname
如果要稍微改变一下:
var vasya = new User("oldName oldSurname");
console.log(vasya.firstName); //
console.log(vasya.lastName); //
vasya.firstName = "newName";
vasya.lastName = "newSurname"
console.log(vasya.fullName);
它返回oldName newSurname
请解释为什么我现在看到 oldName
取代了 newName
最佳答案
我研究了这段代码,发现它是命名冲突的。 这个变体工作正常
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;
}
}
})
}
关于javascript - 为什么 getter 返回旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40785434/