2016-11-24 7 views
2

私は次のコードを持っている。それを少し変更する場合なぜゲッター戻り古い値

var vasya = new User("oldName oldSurname"); 

console.log(vasya.firstName); // 


vasya.firstName = "newName"; 
vasya.lastName = "newSurname" 

console.log(vasya.fullName); 

この出力newName OldSurname

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); // 
console.log(vasya.lastName); // 

vasya.firstName = "newName"; 
vasya.lastName = "newSurname" 

console.log(vasya.fullName); 

それは私が、私はこのコードで演奏し、それが競合を命名していることが分かったnewName

答えて

1

oldName instedを参照してくださいなぜ今oldName newSurname

を説明してください返します。 この変形は、あなたがfullNameValueを参照するか、それはあなたがのparamとして渡されたVARを使用するときは、「この」キーワードを使用する必要が適切に

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

作品

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

} 
関連する問題