## 語法
~~~
constructor([arguments]) { ... }
~~~
## 描述
在一個類中只能有一個名為 “constructor” 的特殊方法。 一個類中出現多次構造函數 (`constructor)`方法將會拋出一個[`SyntaxError`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError "SyntaxError?對象代表嘗試解析語法上不合法的代碼的錯誤。")錯誤。
在一個構造方法中可以使用`super`關鍵字來調用一個父類的構造方法。
如果沒有顯式指定構造方法,則會添加默認的 constructor 方法。
如果不指定一個構造函數(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;
}
}
~~~
### 另一個例子
看看這個代碼片段
~~~js
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
class Rectangle {}
Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
let newInstance = new Square();
console.log(newInstance.name); //Polygon
~~~
這里,**Square**類的原型被改變,但是在正在創建一個新的正方形實例時,仍然調用前一個基類**Polygon**的構造函數。
### 默認構造方法
如前所述,如果不指定構造方法,則使用默認構造函數。對于基類,默認構造函數是:
~~~js
constructor() {}
~~~
對于派生類,默認構造函數是:
~~~js
constructor(...args) {
super(...args);
}
~~~
- 內容介紹
- EcmaScript基礎
- 快速入門
- 常量與變量
- 字符串
- 函數的基本概念
- 條件判斷
- 數組
- 循環
- while循環
- for循環
- 函數基礎
- 對象
- 對象的方法
- 函數
- 變量作用域
- 箭頭函數
- 閉包
- 高階函數
- map/reduce
- filter
- sort
- Promise
- 基本對象
- Arguments 對象
- 剩余參數
- Map和Set
- Json基礎
- RegExp
- Date
- async
- callback
- promise基礎
- promise-api
- promise鏈
- async-await
- 項目實踐
- 標簽系統
- 遠程API請求
- 面向對象編程
- 創建對象
- 原型繼承
- 項目實踐
- Classes
- 構造函數
- extends
- static
- 項目實踐
- 模塊
- import
- export
- 項目實踐
- 第三方擴展庫
- immutable
- Vue快速入門
- 理解MVVM
- Vue中的MVVM模型
- Webpack+Vue快速入門
- 模板語法
- 計算屬性和偵聽器
- Class 與 Style 綁定
- 條件渲染
- 列表渲染
- 事件處理
- 表單輸入綁定
- 組件基礎
- 組件注冊
- Prop
- 自定義事件
- 插槽
- 混入
- 過濾器
- 項目實踐
- 標簽編輯
- iView
- iView快速入門
- 課程講座
- 環境配置
- 第3周 Javascript快速入門