HLJ 发布于
2025-06-11 10:31:54
0阅读

JavaScript Class 基本语法

JavaScript Class 基本语法

在 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)

使用 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 关键字

在子类中,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);

Getters 和 Setters

类也可以包含 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

私有字段 (ES2022)

最新的 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); // 错误: 私有字段无法从类外部访问

注意事项

  1. 类声明不会被提升,必须先声明后使用
  2. 类中的所有代码都自动在严格模式下执行
  3. 类方法是不可枚举的
  4. 类本质上是函数,typeof MyClass 返回 "function"

JavaScript 的类语法提供了一种更清晰、更接近传统面向对象语言的方式来处理对象和继承,但其底层仍然是基于原型的继承机制。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-06-11/819.html
最后生成于 2025-06-13 20:53:24
此内容有帮助 ?
0