javascript - 为什么 getter 返回旧值

标签 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 取代了 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/

相关文章:

java - html表单发布数据

java - 编写一个简单的 HTTP 服务器来接受 GET 请求

python - 遇到 python 错误 <generator object <genexpr>

javascript - Mustache.js 未正确呈现

html - 是否有一种优雅的方式在可以重复使用的新选项卡中打开外部链接?

php - 从我之前的页面加载中自动选择复选框

image - 将弹出图像添加到 Wordpress 中的平面图

Java,发送URL请求并在回复之前关闭?

MYSQL|将值插入 SET 数据类型

java - 列表上的retainAll()会导致java中的错误