2017-01-29 33 views
-1

可能有公共領域的ES6類是這樣的:如何寫公共領域的純ES6

class Device { 

    public id=null; 
    public name=null; 

    constructor(id,name,token) { 
     this.id = id;  // I want this field to be public 
     this.name = id;  // I want this field to be public 

     this.token = token; // this will be private 
    } 
} 

我知道這是很容易通過把他們的構造函數(有私人只是場像'token'字段在上面的示例代碼中) - 但是公共字段呢?

+1

[ES6類變量替代品]的可能的複製(http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives) – Dekel

+1

你所說的「公共意思場「?常規的實例變量已經是公共可訪問的屬性 - 總是(在ES3到ES6中一樣)。所以你的'id'和'name'屬性已經可以被任何擁有你的對象的人訪問。現在你的問題不清楚你要求什麼。 – jfriend00

+0

我的錯誤 - 我不檢查在構造函數中聲明的字段實際上是否是公有的 - 問題在於私有字段 –

回答

4

實際上,如果您在構造函數中爲某個屬性this分配了某些內容,則該字段將是公共的。 ES6課程中沒有私人領域。

class Test { 
 
    constructor(name) { 
 
    this.name = name; 
 
    } 
 
} 
 

 
const test = new Test("Kamil"); 
 
console.log(test.name); // "Kamil"

相關問題