简述怎样通过ES5及ES6声明一个类 ?

在JavaScript中,类(Class)是一种用于创建对象和实现继承结构的语法糖。ES5和ES6提供了不同的方式来声明类。

通过ES5声明类

在ES5中,类和继承是通过函数和原型链来实现的。

示例:声明一个简单的Person类
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
};

// 创建实例
var person1 = new Person('John', 30);
person1.greet(); // 输出: Hello, my name is John and I am 30 years old.

通过ES6声明类

ES6引入了class关键字,提供了一种更清晰、更面向对象的语法来创建类和实现继承。

示例:声明一个简单的Person类
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 person1 = new Person('John', 30);
person1.greet(); // 输出: Hello, my name is John and I am 30 years old.

继承

在ES5中,继承是通过修改原型链来实现的。而在ES6中,继承通过extends关键字以及super()函数来实现。

ES5继承示例
function Student(name, age, grade) {
  Person.call(this, name, age); // 调用父类构造函数
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype); // 设置原型链
Student.prototype.constructor = Student; // 修复构造函数指针

Student.prototype.study = function() {
  console.log(this.name + " is studying.");
};

var student1 = new Student('Jane', 22, 'A');
student1.greet(); // Hello, my name is Jane and I am 22 years old.
student1.study(); // Jane is studying.
ES6继承示例
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // 调用父类构造函数
    this.grade = grade;
  }

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

const student1 = new Student('Jane', 22, 'A');
student1.greet(); // Hello, my name is Jane and I am 22 years old.
student1.study(); // Jane is studying.

ES6的class语法提供了一种更简洁和直观的方式来声明类和实现继承,使得代码更易于理解和维护。

发表评论

后才能评论