在 JavaScript 中,class
是 ES6 (ECMAScript 2015) 引入的一种语法糖,用于创建对象和实现继承,比传统的基于原型的继承更清晰和易于理解。
class MyClass {
// 类方法
constructor() { ... }
method1() { ... }
method2() { ... }
...
}
然后使用 new MyClass()
来创建具有所有列出的方法的新对象。
constructor
是一个特殊方法,用于创建和初始化类创建的对象。
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hello, my name is ${this.name}`);
}
}
let person = new Person("John");
person.sayHi(); // 输出: Hello, my name is John
类中可以定义各种方法:
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
subtract(num) {
this.value -= num;
return this;
}
getValue() {
return this.value;
}
}
const calc = new Calculator();
calc.add(5).subtract(2);
console.log(calc.getValue()); // 输出: 3
使用 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.
在子类中,super
用于调用父类的构造函数和方法:
class Cat extends Animal {
constructor(name, color) {
super(name); // 调用父类的 constructor(name)
this.color = color;
}
speak() {
super.speak(); // 调用父类的 speak 方法
console.log(`${this.name} meows.`);
}
}
const cat = new Cat('Whiskers', 'white');
cat.speak();
// 输出:
// Whiskers makes a noise.
// Whiskers meows.
使用 static
关键字定义静态方法或属性,它们属于类本身而不是实例:
class MyClass {
static staticMethod() {
console.log('This is a static method');
}
static staticProperty = 'Some value';
}
MyClass.staticMethod(); // 直接通过类调用
console.log(MyClass.staticProperty);
类也可以包含 getter 和 setter:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
}
const temp = new Temperature(25);
console.log(temp.fahrenheit); // 77
temp.fahrenheit = 86;
console.log(temp.celsius); // 30
最新的 JavaScript 标准支持真正的私有字段,使用 #
前缀:
class Counter {
#count = 0; // 私有字段
increment() {
this.#count++;
}
get value() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.value); // 1
console.log(counter.#count); // 错误: 私有字段无法从类外部访问
typeof MyClass
返回 "function"JavaScript 的类语法提供了一种更清晰、更接近传统面向对象语言的方式来处理对象和继承,但其底层仍然是基于原型的继承机制。