JavaScript ES6类
引言
在 JavaScript ES6(ECMAScript 2015)之前,JavaScript 是通过原型继承来实现面向对象编程的,这种方式对于熟悉传统面向对象语言的开发者来说可能不太直观。ES6 引入的类(Class)语法提供了一种更清晰、更简洁的方式来创建对象和处理继承,使 JavaScript 的面向对象编程更加接近于 Java、C++ 等语言的风格。
尽管 ES6 类在语法上与其他面向对象语言相似,但在底层实现上,它仍然是基于 JavaScript 的原型继承机制。本文将详细介绍 ES6 类的语法、特性和使用方法。
ES6 类的基本语法
类的定义
使用 class
关键字定义一个类:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
创建实例
使用 new
关键字创建类的实例:
const alice = new Person('Alice', 25);
alice.sayHello(); // 输出: Hello, my name is Alice and I am 25 years old.
类的构成部分
构造函数
constructor
是类的特殊方法,用于创建和初始化类的实例。一个类只能有一个 constructor
方法。
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.brand); // 输出: Toyota
实例方法
在类中定义的方法会被添加到类的原型上,所有实例都可以共享这些方法。
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
const calc = new Calculator();
console.log(calc.add(5, 3)); // 输出: 8
console.log(calc.subtract(5, 3)); // 输出: 2
静态方法
使用 static
关键字定义类的静态方法,这些方法不需要实例化就可以调用,直接通过类名访问。
class MathUtils {
static square(x) {
return x * x;
}
static cube(x) {
return x * x * x;
}
}
console.log(MathUtils.square(3)); // 输出: 9
console.log(MathUtils.cube(3)); // 输出: 27
Getter 和 Setter
类可以包含 getter 和 setter 方法,用于获取和设置类的属性值。
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get celsius() {
return this._celsius;
}
set celsius(value) {
if (value < -273.15) {
throw new Error('Temperature below absolute zero is not possible');
}
this._celsius = value;
}
get fahrenheit() {
return this._celsius * 9/5 + 32;
}
set fahrenheit(value) {
this._celsius = (value - 32) * 5/9;
}
}
const temp = new Temperature(25);
console.log(temp.celsius); // 输出: 25
console.log(temp.fahrenheit); // 输出: 77
temp.celsius = 30;
console.log(temp.celsius); // 输出: 30
console.log(temp.fahrenheit); // 输出: 86
temp.fahrenheit = 68;
console.log(temp.celsius); // 输出: 20
类的继承
ES6 类支持通过 extends
关键字实现继承,这使得代码复用和层次结构的构建变得更加简单。
基本继承
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // 输出: Rex barks.