How to declare a class in ES6? How does a class inherit?

In JavaScript, you use the keyword classto declare a class. A class is a template that is used to create an object's constructor, which contains properties and methods. The following is the basic syntax for declaring a class:

class ClassName {
  constructor() {
    // 构造函数,用于创建对象实例时初始化属性
    this.propertyName = value;
  }

  // 方法定义
  methodName() {
    // 方法体
  }
}

In the above example, ClassNameis the name of the class, constructoris the class's constructor, and is used to initialize the properties of the class. You add properties and initialize an object in the constructor.

To create an instance of a class, you can use newthe keyword as follows:

const instance = new ClassName();

Inheritance is an important concept in object-oriented programming that allows one class to inherit the properties and methods of another class. In JavaScript, you can use extendsthe keyword to create a class inheritance relationship. Here is a simple inheritance example:

class Parent {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 调用父类的构造函数
    this.age = age;
  }

  sayAge() {
    console.log(`${this.name} is ${this.age} years old.`);
  }
}

const child = new Child('Alice', 5);
child.sayHello(); // 输出:Hello, Alice!
child.sayAge();   // 输出:Alice is 5 years old.

In the above example, Childthe class inherits Parentthe properties and methods of class. Use superthe keyword to call the parent class's constructor to initialize the parent class's properties. This allows Childthe class to access Parentthe properties and methods of the class, while also defining its own properties and methods.

Inheritance is a powerful mechanism that allows you to establish relationships between classes and extend or modify the behavior of a parent class in a child class. This is useful in creating complex object models and applications.

Guess you like

Origin blog.csdn.net/m0_74801194/article/details/132847902