面试题答案
一键面试设计思路
- 使用原型链继承:在 JavaScript 中,通过原型链来实现类的继承,这样可以复用基类的属性和方法,同时每个子类也能有自己独特的属性和方法。
- 保持代码的可扩展性:为了方便未来添加新的子类及其专属方法,我们将添加方法的逻辑设计得易于扩展。每个子类在定义时,只需要专注于自己特有的方法,而不需要过多关注继承的通用逻辑。
核心实现代码
// 基类 Vehicle
function Vehicle(brand, model) {
this.brand = brand;
this.model = model;
}
// Car 类继承自 Vehicle
function Car(brand, model) {
Vehicle.call(this, brand, model);
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
// 为 Car 类添加 drive 方法
Car.prototype.drive = function() {
console.log(`Driving a ${this.brand} ${this.model}`);
};
// Truck 类继承自 Vehicle
function Truck(brand, model) {
Vehicle.call(this, brand, model);
}
Truck.prototype = Object.create(Vehicle.prototype);
Truck.prototype.constructor = Truck;
// 为 Truck 类添加 load 方法
Truck.prototype.load = function() {
console.log(`Loading a ${this.brand} ${this.model}`);
};
// 示例使用
const myCar = new Car('Toyota', 'Corolla');
myCar.drive();
const myTruck = new Truck('Ford', 'F-150');
myTruck.load();
这样,后续如果要添加新的继承自 Vehicle
的子类,例如 Motorcycle
,只需要按照类似 Car
和 Truck
的方式定义,并添加其专属方法即可,代码如下:
// Motorcycle 类继承自 Vehicle
function Motorcycle(brand, model) {
Vehicle.call(this, brand, model);
}
Motorcycle.prototype = Object.create(Vehicle.prototype);
Motorcycle.prototype.constructor = Motorcycle;
// 为 Motorcycle 类添加专属方法 ride
Motorcycle.prototype.ride = function() {
console.log(`Riding a ${this.brand} ${this.model}`);
};
// 示例使用
const myMotorcycle = new Motorcycle('Harley - Davidson', 'Fat Boy');
myMotorcycle.ride();