HLJ 发布于
2025-06-11 10:33:14
0阅读

JavaScript 类继承

JavaScript 类继承

在 JavaScript 中,类继承是通过原型链实现的。ES6 引入了 classextends 关键字,使得类继承更加清晰和易于理解。

基本继承语法

class Parent {
  constructor(name) {
    this.name = name;
  }
  
  sayHello() {
    console.log(`Hello, I'm ${this.name}`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 调用父类的constructor
    this.age = age;
  }
  
  sayAge() {
    console.log(`I'm ${this.age} years old`);
  }
}

const child = new Child('Alice', 10);
child.sayHello(); // Hello, I'm Alice
child.sayAge();   // I'm 10 years old

继承的关键点

  1. extends 关键字:用于声明一个类继承另一个类
  2. super 关键字
    • 在构造函数中,super() 必须在使用 this 之前调用
    • 在方法中,super 用于调用父类的方法

方法重写

子类可以重写父类的方法:

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
  
  // 重写父类方法
  sayHello() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old`);
  }
}

const child = new Child('Bob', 8);
child.sayHello(); // Hi, I'm Bob and I'm 8 years old

静态方法继承

静态方法也会被继承:

class Parent {
  static staticMethod() {
    console.log('Parent static method');
  }
}

class Child extends Parent {}

Child.staticMethod(); // Parent static method

检查继承关系

可以使用 instanceof 检查对象是否属于某个类或其父类:

console.log(child instanceof Child);  // true
console.log(child instanceof Parent); // true

继承内置类型

也可以继承 JavaScript 内置类型:

class MyArray extends Array {
  first() {
    return this[0];
  }
  
  last() {
    return this[this.length - 1];
  }
}

const arr = new MyArray(1, 2, 3);
console.log(arr.first()); // 1
console.log(arr.last());  // 3

注意事项

  1. 类继承是基于原型的继承的语法糖
  2. 在构造函数中必须先调用 super() 才能使用 this
  3. 如果子类没有定义构造函数,会默认生成一个并调用 super()
  4. 类不支持多继承,只能继承一个父类

类继承提供了一种更清晰、更接近传统面向对象语言的方式来组织 JavaScript 代码。

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