Class
Class
@TODO
class Foo {constructor (a, b) {this.x = a;this.y = b;}gimmeXY () {return this.x * this.y;} } 復(fù)制代碼- 只能通過(guò)new Foo()來(lái)實(shí)例化,Foo.call(obj)是不允許的
- Foo是不會(huì)提升的,繼承或者實(shí)例化之前要先聲明
構(gòu)造器
對(duì)于類和子類來(lái)說(shuō),構(gòu)造器并不是必須的,如果省略的話會(huì)有默認(rèn)構(gòu)造器。
默認(rèn)子類構(gòu)造器自動(dòng)調(diào)用父類的構(gòu)造器并傳遞所有參數(shù)。
子類構(gòu)造器中調(diào)用super(..)之后才能訪問(wèn)this
class Foo {constructor () {this.a = 1;} }class Bar extends Foo {constructor () {this.b = 2; // 不允許在super()之前super(); // 要改正的話可以交換這兩條語(yǔ)句} } 復(fù)制代碼擴(kuò)展原生類
class myArray extends Array {first () {}last () {} } 復(fù)制代碼元屬性
new.target是undefined的話,這個(gè)函數(shù)不是通過(guò)new調(diào)用的
static
類相當(dāng)于實(shí)例的原型,所有在類中定義的方法,都會(huì)被實(shí)例繼承。如果在一個(gè)方法前,加上static關(guān)鍵字,就表示該方法不會(huì)被實(shí)例繼承,而是直接通過(guò)類來(lái)調(diào)用,這就稱為“靜態(tài)方法”。
class Foo {static classMethod() {return 'hello';} }Foo.classMethod() // 'hello'var foo = new Foo(); foo.classMethod() // TypeError: foo.classMethod is not a function 復(fù)制代碼Symbol.species Getter構(gòu)造器
class MyCoolArray extends Array {static get [Symbol.species]() { return Array } } var a = new MyCoolArray(1, 2, 3); b = a.map((v) => v * 2) b instanceof MyCoolArray; // false b instanceof Array; // true 復(fù)制代碼總結(jié)
- 上一篇: CSS布局问题
- 下一篇: create-react-app 脚手架