2017-03-16 91 views
2

我需要使用setters洞察力ES6 classes自動調用一些方法,當一個實例的某些屬性改變。ES6類 - 錯誤的構造函數和setter行爲

我寫了這個:

class Some { 
    constructor() { 
    this.xPos = 0; 
    this.yPos = 0; 
    } 

    set xPos (value) { 
    console.log(`xPos ${this.xPos}`); 
    } 

    set yPos (value) { 
    console.log(`yPos ${this.yPos}`); 
    } 
} 

let some = new Some(); 

但控制檯輸出:

xPos undefined 
yPos undefined 

回答

4

您不必爲干將和xPosyPos,爲什麼你得到了一個未定義。

這個this.xPos = 0;調用setter爲xPos,但是當你想寫這個值時,它會爲它找到一個變量或一個getter,但是你沒有任何一個。在你的情況下,你需要使用價值,或爲它寫一個吸氣劑。

在我通過getterssetters工作的例子。在setter我設置屬性的值和讀取投擲gettergetter返回屬性的值。

class Some { 
 

 
    constructor() { 
 
    this.xPos = 0; 
 
    this.yPos = 0; 
 
    } 
 

 
    set xPos (value) { 
 
    this.xPosProp = value; 
 
    console.log(`xPos ${this.xPos}`); 
 
    } 
 

 
    set yPos (value) { 
 
    this.yPosProp = value; 
 
    console.log(`yPos ${this.yPos}`); 
 
    } 
 
    
 
    get xPos() { 
 
    return this.xPosProp; 
 
    } 
 

 
    get yPos() { 
 
    return this.yPosProp; 
 
    } 
 
} 
 

 
let some = new Some();

+0

所以,如果我對一些道具提供二傳手我必須爲它提供getter? 應該是這樣的: 得到xPos(){return this.xPos} ? – animatio

+0

@animatio如果你想讀取值傳遞給那個setter,你必須 –

+0

@animatio並且在這裏你需要一個屬性,如果你想存儲數據 –