ES6 class只不過是現有的基于原型繼承機制的一層語法糖,了解這個事實之后,`class`關鍵字對你來說就不再像一個其它語言的概念了。
```
class Box {
constructor(length, width) { this.length = length; this.width = width; }
calculateArea() { return this.length * this.width; }
let box = new Box(2, 2);
box.calculateArea(); // 4
// ES5
function Box(length, width) { this.length = length; this.width = width; } Box.prototype.calculateArea = function() { return this.length * this.width; }
var box = new Box(2, 2);
box.calculateArea(); // 4
```
另外,ES6中還可以用`extends`關鍵字來創建子類。
```
class MyComponent extends React.Component {
// Now MyComponent class contains all React component methods
// such as componentDidMount(), render() and etc.
}
```
#### 構造方法
~~~
constructor([arguments]) { ... }
~~~
在一個類中只能有一個名為 “constructor” 的特殊方法。 一個類中出現多次構造函數 (`constructor)`方法將會拋出一個SyntaxError錯誤。
在一個構造方法中可以使用`super`關鍵字來調用一個父類的構造方法。
如果沒有顯式指定構造方法,則會添加默認的 constructor 方法。
如果不指定一個構造函數(constructor)方法, 則使用一個默認的構造函數(constructor)。
~~~js
class Square extends Polygon {
constructor(length) {
// 在這里, 它調用了父類的構造函數, 并將 lengths 提供給 Polygon 的"width"和"height"
super(length, length);
// 注意: 在派生類中, 必須先調用 super() 才能使用 "this"。
// 忽略這個,將會導致一個引用錯誤。
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
// 注意:不可使用 this.area = value
// 否則會導致循環call setter方法導致爆棧
this._area = value;
}
}
~~~