關於在es6的在class類裏定義箭頭函數會報錯的問題?
阿新 • • 發佈:2018-04-03
val .com HR 構造 col int gpo color 表示
就表示私有屬性
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
加了私有屬性。方法是在屬性名之前,使用#
表示。
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()
)。
私有屬性可以指定初始值,在構造函數執行時進行初始化。
class Point { #x = 0; constructor() { #x; // 0 } }
之所以要引入一個新的前綴#
表示私有屬性,而沒有采用private
關鍵字,是因為 JavaScript 是一門動態語言,使用獨立的符號似乎是唯一的可靠方法,能夠準確地區分一種屬性是否為私有屬性。另外,Ruby 語言使用@
表示私有屬性,ES6 沒有用這個符號而使用#
,是因為@
已經被留給了 Decorator。
該提案只規定了私有屬性的寫法。但是,很自然地,它也可以用來寫私有方法。
class Foo { #a; #b; #sum() { return #a + #b; } printSum() { console.log(#sum()); } constructor(a, b) { #a = a; #b = b; } }
上面代碼中,#sum()
就是一個私有方法。
另外,私有屬性也可以設置 getter 和 setter 方法。
class Counter { #xValue = 0; get #x() { return #xValue; } set #x(value) { this.#xValue = value; } constructor() { super(); // ... } }
上面代碼中,#x
是一個私有屬性,它的讀寫都通過get #x()
和set #x()
來完成。
關於在es6的在class類裏定義箭頭函數會報錯的問題?