首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

constructor

构造函数constructor?是用于创建和初始化类中创建的一个对象的一种特殊方法。

语法

代码语言:javascript
复制
constructor([arguments]) { ... }

描述

在一个类中只能有一个名为 “constructor” 的特殊方法。 一个类中出现多次构造函数 (constructor)方法将会抛出一个 SyntaxError 错误。

在一个构造方法中可以使用super关键字来调用一个父类的构造方法。

如果没有显式指定构造方法,则会添加默认的 constructor 方法。

实例

使用constructor方法

以下代码片段来自?类的实例在线?demo)。

代码语言:javascript
复制
class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  } 
}

另一个例子

看看这个代码片段

代码语言:javascript
复制
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的构造函数。

默认构造方法

如前所述,如果不指定构造方法,则使用默认构造函数。对于基类,默认构造函数是:

代码语言:javascript
复制
constructor() {}

对于派生类,默认构造函数是:

代码语言:javascript
复制
constructor(...args) {
  super(...args);
}

标准

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Constructor Method' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'Constructor Method' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

42.0

(Yes)

45 (45)

?

?

?

Default constructors

?

?

45 (45)

?

?

?

Feature

Android

Android Webview

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Chrome for Android

Basic support

No support

42.0

(Yes)

45.0 (45)

?

?

?

42.0

Default constructors

?

?

?

45.0 (45)

?

?

?

?

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com