# 构造方法

`constructor` 是一种用于创建和初始化`class`创建的对象的特殊方法。

## 语法

```constructor([arguments]) { ... }
```

## 示例

### 使用`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
``````

### 默认构造方法

js

``````constructor() {}
``````

js

``````constructor(...args) {
super(...args);
}
``````

## 浏览器兼容性

BCD tables only load in the browser
{"ft_lang_label":"__label__zh","ft_lang_prob":0.6178454,"math_prob":0.8869701,"size":1472,"snap":"2023-40-2023-50","text_gpt3_token_len":568,"char_repetition_ratio":0.17438692,"word_repetition_ratio":0.013605442,"special_character_ratio":0.23777173,"punctuation_ratio":0.1981132,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9737043,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-12-02T00:13:45Z\",\"WARC-Record-ID\":\"<urn:uuid:3a1558b5-6467-488d-aa9a-8c03a5f30ada>\",\"Content-Length\":\"140570\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:06b02bdc-0851-49d1-a267-be97b0999075>\",\"WARC-Concurrent-To\":\"<urn:uuid:a607a2ad-222b-450c-a6af-53a003f2e635>\",\"WARC-IP-Address\":\"34.111.97.67\",\"WARC-Target-URI\":\"https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/constructor\",\"WARC-Payload-Digest\":\"sha1:NWO4YHR2SI3MRKQ2TPTIR2DLBS6JY6XK\",\"WARC-Block-Digest\":\"sha1:JVCMPNXLMHC4KSY7AAYPO36HF32OIP7I\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100308.37_warc_CC-MAIN-20231201215122-20231202005122-00640.warc.gz\"}"}