
JavaScript 中的class写法
2025-02-21 03:07:35
2025-02-22 11:52:21
1. 基本写法
js
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.`);
}
}
创建实例
js
const person = new Person('John', 30);
person.sayHello(); // 输出: Hello, my name is John and I am 30 years old.
constructor 方法:是类的构造函数,用于初始化类的实例。它会在创建对象时自动调用。
实例方法:在类中定义的普通方法,可以通过实例调用。
2. 类的继承
JavaScript 的类支持继承,使用 extends 关键字可以实现子类继承父类。
js
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类的构造函数
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // 输出: Buddy barks.
extends 关键字:用于声明子类继承父类。
super() 方法:在子类的构造函数中调用父类的构造函数,用于初始化继承的属性。
3. 静态方法
静态方法是属于类本身的方法,而不是类的实例。静态方法可以通过类名直接调用,而不需要创建实例。
js
class MathUtils {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathUtils.add(5, 3)); // 输出: 8
console.log(MathUtils.multiply(5, 3)); // 输出: 15
4. Getter 和 Setter
类可以使用 get 和 set 关键字来定义属性的访问器方法,用于封装属性的读取和设置逻辑。
js
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
this._name = value.trim();
}
}
const user = new User(' John Doe ');
console.log(user.name); // 输出: JOHN DOE
user.name = 'Jane Smith ';
console.log(user.name); // 输出: JANE SMITH
get 方法:定义了如何读取属性的值。
set 方法:定义了如何设置属性的值。
5. 静态属性和实例属性
实例属性:通过 this 定义在构造函数中,每个实例都有自己的副本。
静态属性:通过类名直接访问,属于类本身,而不是实例。
language
class MyClass {
constructor(value) {
this.instanceProperty = value; // 实例属性
}
static staticProperty = 'Static Value'; // 静态属性
}
const instance = new MyClass('Instance Value');
console.log(instance.instanceProperty); // 输出: Instance Value
console.log(MyClass.staticProperty); // 输出: Static Value
6. 私有属性和方法(ES2020+)
私有属性和方法只能在类的内部访问,不能通过类的实例或子类直接访问。
js
class Counter {
#count = 0; // 私有属性
increment() {
this.#count++;
console.log(`Count is now ${this.#count}`);
}
#reset() { // 私有方法
this.#count = 0;
console.log('Count has been reset.');
}
}
const counter = new Counter();
counter.increment(); // 输出: Count is now 1
counter.increment(); // 输出: Count is now 2
// counter.#reset(); // 错误:私有方法无法从外部访问
总结
class 是一种语法糖,底层仍然是基于原型链实现的。
类的写法更加直观,适合面向对象编程。
使用 class 可以实现继承、封装、多态等面向对象的特性。
目录