ES5 和 ES6 类的实现
1. 定义方式
ES5:通过构造函数和原型链模拟类
// 构造函数作为类的定义
function Person(name) {this.name = name;
}// 原型上定义方法
Person.prototype.sayHello = function() {console.log("Hello, " + this.name);
};
ES6:使用 class
关键字声明类,语法更简洁清晰
class Person {// 构造方法constructor(name) {this.name = name;}// 类方法(自动添加到原型)sayHello() {console.log(`Hello, ${this.name}`);}
}
2. 继承实现
ES5:通过 call/apply
继承属性,Object.create
继承方法
function Student(name, grade) {// 继承属性Person.call(this, name);this.grade = grade;
}// 继承方法
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;// 子类方法
Student.prototype.study = function() {console.log(`${this.name} is studying`);
};
ES6:使用 extends
关键字声明继承,super
调用父类
class Student extends Person {constructor(name, grade) {// 必须先调用super()super(name);this.grade = grade;}study() {console.log(`${this.name} is studying`);}
}
3. 方法定义
- ES5:所有方法需显式添加到原型上
- ES6:类体内直接定义方法,自动成为原型方法,无需手动绑定原型
4. 静态方法
ES5:直接挂载到构造函数上
Person.create = function(name) {return new Person(name);
};
ES6:使用
static
关键字声明
class Person {static create(name) {return new Person(name);}
}
总结
ES6 的 class
本质上是 ES5 原型继承的语法糖,但提供了更清晰、更接近传统面向对象语言的语法,同时增加了一些新特性,使类的定义和继承更加直观和易于维护。不过,理解 ES5 的原型实现有助于深入掌握 JavaScript 的面向对象本质。