1. 原型链模式继承
function Parent() {
this.name = 'parent';
}
function Child() {
this.type = 'child';
}
Child.prototype = new Parent();
/* Child.prototype.constructor = Child; */
- 重点:让新实例的原型等于父类的实例。
- 特点:1、实例可继承的属性有:实例的构造函数的属性,父类构造函数属性,父类原型的属性。(新实例不会继承父类实例的属性!)
- 缺点:1、新实例无法向父类构造函数传参。
2、继承单一。
3、所有新实例都会共享父类实例的属性。(原型上的属性是共享的,一个实例修改了原型属性,另一个实例的原型属性也会被修改!)
function Parent() {
this.name = 'parent';
this.play = [1, 2, 3];
}
function Child() {
this.type = 'child';
}
Child.prototype = new Parent();
var s1 = new Child();
var s2 = new Child();
s1.play.push(4);
s1.play // [1, 2, 3, 4]
s2.play // [1, 2, 3, 4]
s1.play === s2.play // true
2. 构造承数模式继承
function Parent() {
this.name = 'parent';
}
function Child() {
Parent.call(this);
this.type = 'child';
}
- 重点:用.call()和.apply()将父类构造函数引入子类函数。
- 特点:1、只继承了父类构造函数的属性,没有继承父类原型的属性。
2、解决了原型链继承的部分缺点。
3、可以继承多个构造函数属性(call多个)。
4、在子实例中可向父实例传参。 - 缺点:1、只能继承父类构造函数的属性。
2、无法实现构造函数的复用。(每次用每次都要重新调用)。
3、每个新实例都有父类构造函数的副本,臃肿。
3. 组合模式继承
组合原型链继承和借用构造函数继承,常用。
function Parent(name) {
this.name = name;
}
function Child() {
Parent.call(this);
this.type = 'child';
}
Child.prototype = new Parent();
/* Child.prototype.constructor = Child; */
- 重点:结合了两种模式的优点,传参和复用
- 特点:1、可以继承父类原型上的属性,可以传参,可复用。
2、每个新实例引入的构造函数属性是私有的。 - 缺点:调用了两次父类构造函数(耗内存),子类的构造函数会代替原型上的那个父类构造函数。
4. 寄生模式继承
共享原型。
function Parent() {
this.name = 'parent';
}
function Child() {
this.type = 'child';
}
Child.prototype = Parent.prototype;
constructor指向不对,也不能修改原型链,可使用下面的方式。
function Parent() {
this.name = 'parent';
}
function Child() {
this.type = 'child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
5. 圣杯模式继承(寄生组合模式继承)
利用空对象作为中介,空对象几乎不占内存,让空对象的原型指向父亲的原型,让儿子的原型不是直接指向父亲,而是指向空对象的实例,这样也能继承到父亲上的属性,改变时又不会互相影响。
用一个立即执行函数,把媒介 function F(){} 有关的变成闭包,私有化,外面访问不了,这就是最终版的圣杯模式。
let inherit = (function() {
var F = function(){};
return function(Target,Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}())
function Parent() {
this.name = 'parent';
}
function Child() {
this.type = 'child';
}
inherit(Child, Parent)
let child= new Child();
let parent = new Parent();
- ES6 extends 继承
class Parent {}
class Child extends Parent {}

本文详细解读了JavaScript中的原型链继承、构造函数模式、组合继承等,比较它们的特点、优缺点,并介绍了ES6的extends继承。了解原型链如何工作,以及如何选择最适合的继承策略以避免共享属性问题和内存消耗。
382

被折叠的 条评论
为什么被折叠?



