面试题答案
一键面试- 代码复用
- 优势阐述:通过继承,子类可以复用父类的属性和方法,减少重复代码的编写。这提高了代码的可维护性和开发效率,当父类的某个方法需要修改时,只需要在父类中修改一处,所有子类都会受到影响。
- 代码示例:
// 定义父类
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name +'makes a sound.');
};
// 定义子类
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 创建Dog实例
let myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak();// 复用了Animal的speak方法,输出:Buddy makes a sound.
- 层次结构清晰
- 优势阐述:继承使得对象之间的关系更加清晰,形成一种层次结构。这种结构便于理解和扩展,开发者可以很直观地知道哪些对象具有相似的属性和行为,以及它们之间的继承关系。
- 代码示例:
// 父类Vehicle
function Vehicle(type) {
this.type = type;
}
Vehicle.prototype.move = function() {
console.log(this.type +'is moving.');
};
// 子类Car继承自Vehicle
function Car(model) {
Vehicle.call(this, 'Car');
this.model = model;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
// 子类Bicycle继承自Vehicle
function Bicycle() {
Vehicle.call(this, 'Bicycle');
}
Bicycle.prototype = Object.create(Vehicle.prototype);
Bicycle.prototype.constructor = Bicycle;
// 创建实例
let myCar = new Car('Toyota Corolla');
let myBike = new Bicycle();
myCar.move();// 输出:Car is moving.
myBike.move();// 输出:Bicycle is moving.
这里可以清晰看到Car和Bicycle都继承自Vehicle,它们在功能上有共性(move方法),同时又有各自的特性。 3. 多态性
- 优势阐述:继承与多态性紧密相关。子类可以重写父类的方法,在不同的子类中对同一个方法有不同的实现,从而实现多态。这使得代码更加灵活,根据对象的实际类型来调用合适的方法。
- 代码示例:
// 父类Shape
function Shape() {}
Shape.prototype.area = function() {
return 0;
};
// 子类Circle继承自Shape
function Circle(radius) {
this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.area = function() {
return Math.PI * this.radius * this.radius;
};
// 子类Rectangle继承自Shape
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.area = function() {
return this.width * this.height;
};
// 创建实例并调用area方法
let circle = new Circle(5);
let rectangle = new Rectangle(4, 5);
console.log(circle.area());// 输出:78.53981633974483
console.log(rectangle.area());// 输出:20
这里Circle和Rectangle都继承自Shape,但对area方法有不同的实现,体现了多态性。