In JavaScript, you use the keyword class
to 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, ClassName
is the name of the class, constructor
is 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 new
the 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 extends
the 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, Child
the class inherits Parent
the properties and methods of class. Use super
the keyword to call the parent class's constructor to initialize the parent class's properties. This allows Child
the class to access Parent
the 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.