2016-11-24 92 views
2

我有以下代码:为什么吸气返回旧值

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 insted的的newName

回答

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

您必须使用“本”关键字时,您引用fullNameValue否则将使用您的PARAM通过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; 
      } 
     } 
    }) 

}