JavaScript Class constructor ɗanin

定义和用法

constructor() 方法是一种特殊的方法,用于创建和初始化在类中创建的对象。

当初始化类时,constructor() 方法将自动调用,并且必须使用确切的名称 "constructor",实际上,如果您没有构造方法,JavaScript 将添加一个不可见的空构造方法。

Note:A class cannot use multiple constructor() methods. This will throw SyntaxError.

You can use super() methods to call the parent class constructor (see more examples below).

Instance

Example 1

Create a Car class, then create an object named "mycar" based on this Car class:

class Car {
  constructor(brand) {  // Constructor
    this.carname = brand;
  }
}
mycar = new Car("Ford");

Try it yourself

Example 2

To create class inheritance, use Extends Keyword.

Classes created by class inheritance will inherit all methods from another class.

Create a class named "Model" that will inherit the methods of the "Car" class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}
class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();

Try it yourself

super() method ƙarƙarararar ƙaɗaɗa.

By calling in the constructor super() Method, aminuwa zaɗaɗɗa ƙarƙarararar ƙaɗaɗa, aminuwa da kuma ƙarƙarararar ƙaɗaɗa.

Grammar

constructor(parameters)

Technical details

JavaScript Version: ECMAScript 2015 (ES6)

Support ƙarƙarararar

Method Chrome IE Firefox Safari Opera
constructor() 49.0 13.0 45.0 9.0 36.0

Ƙarƙararon kewaye

JavaScript ƙoyarwa:JavaScript ɗanin

JavaScript ƙoyarwa:JavaScript ES6 (EcmaScript 2015)

JavaScript reference manual:Extends keyword

JavaScript reference manual:Super keyword