面试题答案
一键面试构造函数模式实现继承
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log(this.name);
};
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
优点:
- 可以向父构造函数传递参数。
- 每个实例都有自己的属性副本,相互独立,不会互相影响。
缺点:
- 方法都定义在构造函数中,每个实例都会创建相同的方法,造成内存浪费。
- 无法复用父构造函数的原型方法。
原型模式实现继承
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.age = 20;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
优点:
- 方法定义在原型上,所有实例共享,节省内存。
缺点:
- 实例共享原型上的属性和方法,如果修改原型上的引用类型属性,会影响所有实例。
- 创建子类型实例时,无法向父类型构造函数传递参数。
组合继承模式实现继承
function Parent(name) {
this.name = name;
this.friends = ['John', 'Jane'];
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
优点:
- 融合了构造函数模式和原型模式的优点,既可以向父构造函数传递参数,又能实现方法的复用。
缺点:
- 父构造函数会被调用两次,一次在
Child
构造函数中,一次在设置Child.prototype
时,产生不必要的开销。