2016-12-18 159 views
-2

我想要做的是創建一個變量,我可以在類中的不同函數中使用該變量。但由於某些原因,每當我寫let variable構造上面我得到'Unexpected token. A constructor, method, accessor, or property was expected.在一個類中創建一個es6變量全局變量

與VAR嘗試過了,我幾乎得到了相同的結果

class ClassName { 
 

 
    let variable; 
 

 
    constructor() { 
 
    variable = 1; 
 
    } 
 
    
 
    function() { 
 
    console.log(variable + 1); 
 
    } 
 
    
 
}

+1

參見[類](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes)。 –

回答

3

你應該訪問的變量的this屬性:

class ClassName { 
 
    constructor() { 
 
    this.variable = 1; 
 
    } 
 
    someOtherFunction() { 
 
    console.log(this.variable + 1); // 2 
 
    } 
 
} 
 

 
new ClassName().someOtherFunction();

上MDN
相關問題