面试题答案
一键面试原型链继承
- 原理:将子类的原型指向父类的实例,使得子类可以访问父类原型上的属性和方法。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
- 缺点:
- 所有子类实例共享父类实例的属性,如果父类实例属性是引用类型,一个子类实例修改会影响其他实例。
- 创建子类实例时,无法向父类构造函数传参。
构造函数继承
- 原理:在子类构造函数内部通过
call
或apply
调用父类构造函数,将父类的属性和方法绑定到子类实例上。
function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name);
}
- 缺点:
- 子类无法继承父类原型上的方法,只能继承父类构造函数中的属性和方法。
- 每个子类实例都有一份父类构造函数中定义的属性副本,造成内存浪费。
组合继承
- 原理:结合原型链继承和构造函数继承。通过原型链继承父类原型上的方法,通过构造函数继承父类构造函数中的属性。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
- 缺点:
- 调用了两次父类构造函数,一次是在
Child.prototype = new Parent()
,另一次是在Parent.call(this, name)
,造成了不必要的开销。
- 调用了两次父类构造函数,一次是在
寄生组合继承
- 原理:通过创建一个临时构造函数,将其原型指向父类原型,然后创建这个临时构造函数的实例,并将其作为子类的原型。这样既避免了多次调用父类构造函数,又能让子类继承父类原型上的方法。
function inheritPrototype(Child, Parent) {
let prototype = Object.create(Parent.prototype);
prototype.constructor = Child;
Child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
- 优点:
- 只调用了一次父类构造函数,避免了组合继承中重复调用父类构造函数的问题,性能更优。
- 实现了子类对父类原型方法的继承,同时每个子类实例都有自己独立的属性。
性能更优方式及原因:寄生组合继承在性能上更优。因为它既实现了子类对父类原型方法的继承,又避免了组合继承中两次调用父类构造函数带来的性能开销,使得内存使用更合理,创建子类实例时效率更高。