博主头像
<CodeEra />

心存敬畏 行有所止

ES6中class语法和继承的原理

ES6 引入了 class 语法,使得 JavaScript 的面向对象编程更加直观和易用。class 语法本质上是基于原型继承的语法糖,它简化了构造函数和原型方法的定义。

1. Class 语法

1.1 基本语法

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person = new Person('Alice', 25);
person.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
  • constructor 方法是类的构造函数,用于初始化对象的属性。
  • greet 是类的方法,定义在类的原型上。

1.2 静态方法

静态方法属于类本身,而不是类的实例。可以通过类名直接调用。

class Person {
  static info() {
    console.log('This is a Person class.');
  }
}

Person.info(); // 输出: This is a Person class.

2. 继承

ES6 的 class 语法支持通过 extends 关键字实现继承。

2.1 基本继承

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // 调用父类的构造函数
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying in grade ${this.grade}.`);
  }
}

const student = new Student('Bob', 20, 12);
student.greet(); // 输出: Hello, my name is Bob and I am 20 years old.
student.study(); // 输出: Bob is studying in grade 12.
  • super 关键字用于调用父类的构造函数或方法。
  • Student 类继承了 Person 类的属性和方法,并可以添加自己的属性和方法。

2.2 方法重写

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

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}, I am ${this.age} years old, and I am in grade ${this.grade}.`);
  }
}

const student = new Student('Charlie', 18, 10);
student.greet(); // 输出: Hello, my name is Charlie, I am 18 years old, and I am in grade 10.

3. 原理

3.1 原型链

ES6 的 class 语法本质上是基于原型链的继承。classextends 关键字只是语法糖,底层仍然是通过原型链来实现继承。

class Person {
  constructor(name) {
    this.name = name;
  }
}

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
}

// 等价于以下 ES5 代码
function Person(name) {
  this.name = name;
}

function Student(name, grade) {
  Person.call(this, name);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

3.2 super 关键字

super 关键字在子类中有两种用法:

  1. 在构造函数中super() 调用父类的构造函数。
  2. 在方法中super.method() 调用父类的方法。

super 实际上是通过 [[HomeObject]] 内部属性来找到父类的原型方法。

4. 总结

  • ES6 的 class 语法使得 JavaScript 的面向对象编程更加直观和易用。
  • classextends 是基于原型链的语法糖,底层仍然是原型继承。
  • super 关键字用于调用父类的构造函数或方法。
  • 子类可以重写父类的方法,并且可以通过 super 调用父类的实现。

通过 class 语法,JavaScript 的面向对象编程变得更加清晰和易于维护。

发表新评论