ES6 class 详解
ES6(ECMAScript 2015)引入了 class
关键字,它提供了一种更简洁、更面向对象的方式来创建和管理对象。下面将详细介绍 class
的相关内容,包括其中的 API 并给出示例。
1. 基本的 class
定义
在 ES6 里,可借助 class
关键字来定义一个类。下面是一个简单示例:
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return `My name is ${this.name} and I am ${this.age} years old.`;
}
}
let person1 = new Person('John', 30);
console.log(person1.introduce());
在这个例子中:
constructor
是类的构造函数,在创建类的实例时会自动调用,用于初始化对象的属性。introduce
是类的一个方法,通过实例可以调用该方法。
2. 类的继承
使用 extends
关键字能让一个类继承另一个类的属性和方法。以下是示例:
javascript
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
return `${this.name} is studying in grade ${this.grade}.`;
}
}
let student1 = new Student('Jane', 15, 10);
console.log(student1.introduce());
console.log(student1.study());
在这个例子中:
Student
类继承自Person
类。super
关键字在constructor
里调用父类的构造函数,对父类的属性进行初始化。study
是Student
类特有的方法。
3. 静态方法
静态方法属于类本身,并非类的实例。可以使用 static
关键字来定义静态方法。示例如下:
javascript
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(2, 3));
在这个例子中,add
是 MathUtils
类的静态方法,通过类名就可以调用,而不需要创建类的实例。
4. Getter 和 Setter 方法
Getter 和 Setter 方法用于获取和设置对象的属性,可使用 get
和 set
关键字来定义。示例如下:
javascript
class Circle {
constructor(radius) {
this._radius = radius;
}
get area() {
return Math.PI * this._radius * this._radius;
}
set radius(newRadius) {
if (newRadius < 0) {
throw new Error('Radius cannot be negative.');
}
this._radius = newRadius;
}
}
let circle = new Circle(5);
console.log(circle.area);
circle.radius = 10;
console.log(circle.area);
在这个例子中:
get area
是一个 getter 方法,当访问circle.area
时会自动调用该方法。set radius
是一个 setter 方法,当给circle.radius
赋值时会自动调用该方法。
完整示例
javascript
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
makeSound() {
return `${this.name} says ${this.sound}.`;
}
static getType() {
return 'Animal';
}
}
class Dog extends Animal {
constructor(name) {
super(name, 'Woof');
}
wagTail() {
return `${this.name} is wagging its tail.`;
}
}
let dog = new Dog('Buddy');
console.log(dog.makeSound());
console.log(dog.wagTail());
console.log(Animal.getType());
在这个完整示例中:
Animal
类有一个构造函数、一个实例方法makeSound
和一个静态方法getType
。Dog
类继承自Animal
类,有自己的构造函数和特有的方法wagTail
。
通过上述示例,你应该能对 ES6 类的基本概念、继承、静态方法、Getter 和 Setter 方法有更深入的理解。