-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
index.md
76 lines (52 loc) · 1.82 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
---
title: 建構子
slug: Web/JavaScript/Reference/Classes/constructor
---
{{jsSidebar("Classes")}}
`constructor`(建構子)是個隨著 `class` 一同建立並初始化物件的特殊方法。
## 語法
```plain
constructor([arguments]) { ... }
```
## 敘述
一個 class 只能有一個稱為 constructor 的特殊物件。如果一個 class 出現兩次以上的 `constructor`,就會發生 {{jsxref("SyntaxError")}} 錯誤。
如果不指定建構子,就會使用預設的建構子。
## 示例
### 使用 `constructor` 方法
這段程式碼是從 [classes sample](https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html) 擷取而來。([線上範例](https://googlechrome.github.io/samples/classes-es6/index.html))
```js
class Square extends Polygon {
constructor(length) {
// 我們在這裡呼叫了 class 的建構子提供多邊形的長寬值
super(length, length);
// 注意:在 derived class 中,super() 必須在使用 this 以前被呼叫。不這樣的話會發生錯誤。
this.name = "Square";
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
```
### 預設的建構子
如上文所說:如果不指定建構子,就會使用預設的建構子。對 base classes 而言,預設的建構子長得像這樣:
```js
constructor() {}
```
對 derived class 而言,預設的建構子長得像這樣:
```js
constructor(...args) {
super(...args);
}
```
## 規範
{{Specifications}}
## 瀏覽器相容性
{{Compat}}
## 參見
- [super()](/zh-TW/docs/Web/JavaScript/Reference/Operators/super)
- [`class` expression](/zh-TW/docs/Web/JavaScript/Reference/Operators/class)
- [`class` declaration](/zh-TW/docs/Web/JavaScript/Reference/Statements/class)
- [Classes](/zh-TW/docs/Web/JavaScript/Reference/Classes)