为什么getter返回旧值

时间:2016-11-24 11:37:47

标签: javascript get set

我有以下代码:

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 {/ 1}} newName

2 个答案:

答案 0 :(得分:1)

我玩这个代码,发现它是命名冲突。 这个变种正常工作

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;
                }
            }
        })

}

答案 1 :(得分:1)

你必须使用"这个"引用fullNameValue时的关键字,或者它将使用您作为参数传递的var

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;
            }
        }
    })

}