ES6 class 语法实现
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks.`);
}
}
ES5 构造函数模式实现
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(`${this.name} barks.`);
};
继承机制主要区别
- 语法简洁性:
- ES6 class 语法更简洁直观,使用
class
、extends
等关键字,更接近传统面向对象编程语言的写法。
- ES5 构造函数模式相对复杂,需要手动设置原型链(
Object.create
)和借用构造函数(call
)等操作。
- 内部机制:
- ES6 class 是基于 ES5 构造函数和原型链的语法糖。它在底层依然使用原型链来实现继承,但提供了更清晰的语法结构。
- ES5 构造函数模式中,子类通过
Object.create
创建一个新对象,其 __proto__
指向父类的原型对象,从而实现继承,并且通过 call
方法在子类构造函数中调用父类构造函数来初始化实例属性。
- 函数提升:
- ES6 class 不存在函数提升,在定义之前不能使用。
- ES5 构造函数存在函数提升,可以在定义之前使用。