class和extends分别是什么,它们有什么作用?

305 阅读1分钟

在 JavaScript 中,classextends 是面向对象编程(OOP)的关键字,它们用于实现继承的功能。以下是它们的详细解释和作用:


一、class 关键字

1. 定义类

class 用于声明一个类(Class),它是对象的模板,定义了对象的属性方法

  • 类通过 constructor 方法定义构造函数(初始化对象)。
  • 其他方法是类的行为(功能)。

示例:

class Animal {
  constructor(name) {
    this.name = name; // 属性
  }

  // 方法
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

const dog = new Animal("Rex");
dog.speak(); // 输出: "Rex makes a noise."

二、extends 关键字

1. 实现继承

extends 用于创建一个类作为另一个类的子类(派生类),实现继承。

  • 子类会继承父类的属性和方法
  • 子类可以添加新方法,或覆盖父类的方法(重写)。

示例:

class Dog extends Animal { // Dog 继承 Animal
  constructor(name, breed) {
    super(name); // 调用父类构造函数(必须先用 super)
    this.breed = breed;
  }

  // 重写父类方法
  speak() {
    console.log(`${this.name} barks!`);
  }

  // 新增方法
  fetch() {
    console.log(`${this.name} fetches the ball.`);
  }
}

const myDog = new Dog("Buddy", "Golden");
myDog.speak(); // 输出: "Buddy barks!"
myDog.fetch(); // 输出: "Buddy fetches the ball."

三、核心作用

关键字作用核心场景
class定义对象模板封装数据和行为(属性和方法)
extends实现继承复用代码、扩展功能(子类继承父类)

四、关键细节

  1. super 关键字

    • 在子类中,super() 必须在构造函数中调用父类构造函数(否则报错)。
    • 也可用 super.method() 调用父类的方法。
  2. 静态方法和属性

    • static 关键字定义,属于类本身(而非实例)。
    class MathUtils {
      static PI = 3.14159; // 静态属性
      static add(a, b) {   // 静态方法
        return a + b;
      }
    }
    console.log(MathUtils.add(2, 3)); // 5
    

五、与传统原型的区别

classextends 是 ES6 引入的语法糖,底层仍基于 JavaScript 的原型链机制,但代码更简洁直观:

// ES5 原型链写法(等价于 class)
function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  console.log(this.name + " makes a noise.");
};

// ES6 写法更清晰
class Animal {
  constructor(name) { /* ... */ }
  speak() { /* ... */ }
}

总结

  • class:定义对象的模板,封装数据和行为。
  • extends:实现继承,复用和扩展代码。
  • super:调用父类构造函数或方法。
  • 二者结合可以实现面向对象编程的封装、继承、多态特性。