js中的多种继承方法总结

构造函数继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Parent1() {
this.name = "Parent1";
this.arr = [1, 2];
}
Parent1.prototype.sayName = function() {
console.log("this.name", this.name);
};
function Child1() {
Parent1.call(this);
this.childName = "child1";
}

let o1 = new Child1();
let o2 = new Child2();
console.log("o1,o2", o1, o2);
o1.arr.push(3);
console.log("o1,o2", o1, o2);

通过原型链继承

1
2
3
4
5
6
7
8
function Parent2() {
this.name = "Parent2";
this.arr = [1, 2];
}
function Child2() {
this.childName = "child2";
}
Child2.prototype = new Parent();

组合式的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Parent3() {
this.name = "parent3";
this.arr = [1, 2];
}
function Child3() {
Parent3.call(this);
this.childName = "child3";
}
//第一种:这样的缺点是一共进行了两次new 操作
Child3.prototype = new Parent3();
//第二种:问题是由Child3创建的实例 原型链既有Child3也有Parent3
Child3.prototype = Parent3.prototype;
//第三种
Child3.prototype = Object.create(Parent3.prototype);
Child3.prototype.constructor = Child3;