class App { constructor() { this.handleClick = () => { console.log('this is:', this); } } // handleClick1 = () => { // console.log('this is:', this); // } handleClick2(){ console.log('this is:', this); } } const app = new App(); app.handleClick();//this is: App { handleClick: [Function] } // app.handleClick1();//會報錯 app.handleClick2();//this is: App { handleClick: [Function] }
解釋一下:
與私有方法同樣,ES6 不支持私有屬性。目前,有一個提案,爲class
加了私有屬性。方法是在屬性名以前,使用#
表示。git
class Point { #x; constructor(x = 0) { #x = +x; // 寫成 this.#x 亦可 } get x() { return #x } set x(value) { #x = +value } }
上面代碼中,#x
就表示私有屬性x
,在Point
類以外是讀取不到這個屬性的。還能夠看到,私有屬性與實例的屬性是能夠同名的(好比,#x
與get x()
)。github
私有屬性能夠指定初始值,在構造函數執行時進行初始化。app
class Point { #x = 0; constructor() { #x; // 0 } }
之因此要引入一個新的前綴#
表示私有屬性,而沒有采用private
關鍵字,是由於 JavaScript 是一門動態語言,使用獨立的符號彷佛是惟一的可靠方法,可以準確地區分一種屬性是否爲私有屬性。另外,Ruby 語言使用@
表示私有屬性,ES6 沒有用這個符號而使用#
,是由於@
已經被留給了 Decorator。函數
該提案只規定了私有屬性的寫法。可是,很天然地,它也能夠用來寫私有方法。this
class Foo { #a; #b; #sum() { return #a + #b; } printSum() { console.log(#sum()); } constructor(a, b) { #a = a; #b = b; } }
上面代碼中,#sum()
就是一個私有方法。spa
另外,私有屬性也能夠設置 getter 和 setter 方法。code
class Counter { #xValue = 0; get #x() { return #xValue; } set #x(value) { this.#xValue = value; } constructor() { super(); // ... } }
上面代碼中,#x
是一個私有屬性,它的讀寫都經過get #x()
和set #x()
來完成。blog