Javascript 为什么getter返回旧值
我有以下代码:Javascript 为什么getter返回旧值,javascript,get,set,Javascript,Get,Set,我有以下代码: function User(fullName) { this.fullName = fullName; Object.defineProperties(this, { firstName: { get: function () { return fullName.split(" ")[0]; }
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-oldnamname
如果要稍微更改它:
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;
}
}
})
}
引用fullNameValue时必须使用“this”关键字,否则它将使用作为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;
}
}
})
}