虽然 ES6 引入了
class
和
extends
关键字,这两个关键字提供了一种更接近于传统类继承的语法糖,但实际上它们仍然是基于原型链的。
下面来看一个栗子:
// 定义一个构造函数 functionCar(brand, color){ this.brand = brand; this.color = color; } // 在 Car 的原型上添加一个方法 Car.prototype.drive=function(){ return"The "+this.brand +" "+this.color +" car is driving away."; }; // 创建一个 Car 的实例 let redCar =newCar("BMW","red"); // 访问实例的属性 console.log(redCar.brand);// 输出 "BMW" console.log(redCar.color);// 输出 "red" // 调用实例继承自原型的方法 console.log(redCar.drive());// 输出 "The BMW red car is driving away." // 创建一个继承自 Car 的新构造函数 functionElectricCar(brand, color, batteryRange){ // 调用 Car 的构造函数,继承其属性 Car.call(this, brand, color); this.batteryRange = batteryRange; } // 设置 ElectricCar 的原型为 Car 的实例,从而继承 Car 的方法 ElectricCar.prototype =Object.create(Car.prototype); ElectricCar.prototype.constructor = ElectricCar; // 添加 ElectricCar 特有的方法
ElectricCar.prototype.recharge=function(){ return"The "+this.brand +" is recharging."; }; // 创建一个 ElectricCar 的实例 let tesla =newElectricCar("Tesla","blue",300); // 访问继承的属性和方法 console.log(tesla.brand);// 输出 "Tesla" console.log(tesla.drive());// 输出 "The Tesla blue car is driving away." // 访问 ElectricCar 特有的方法 console.log(tesla.recharge());// 输出 "The Tesla is recharging."
在这个例子中定义了一个
Car
构造函数和一个 ElectricCar 构造函数。
ElectricCar
通过将其原型设置为 Car 的一个实例来继承
Car
的属性和方法。我们还为
ElectricCar
添加了一个特有的方法
recharge
。这样,
ElectricCar
的实例 tesla 就可以访问继承自
Car
的属性和方法,以及
ElectricCar
特有的方法。