原型链继承
特点:实例可继承的属性有:实例的构造函数的属性,父类构造函数的属性,父类原型的属性
缺点:原型上的属性是共享的,一个实例修改了原型属性,另一个实例的原型属性也会被修改,并且实例无法向构造函数传参
//原型链继承
function Parent() {
this.name = "parent";
this.play = [1, 2, 3, 4];
}
function Child() {
this.type = "child";
}
Child.prototype = new Parent();
let c1 = new Child();
let c2 = new Child();
c1.play.push(5);
console.log(c1.play); //[1,2,3,4,5]
console.log(c2.play); //[1,2,3,4,5]
构造函数继承
特点:用.call或.apply将父类构造函数引入子类函数,可以继承多规格构造函数(call多个)
缺点:只继承了父类构造函数的属性,没有继承父类原型上的属性
//构造函数继承
function Parent() {
this.name = "parent";
this.play = [1, 2, 3, 4];
}
Parent.prototype.getName = function () {
return this.name;
};
function Child() {
Parent.call(this);
this.type = "child";
}
let c1 = new Child();
let c2 = new Child();
c1.play.push(5);
console.log(c1.play); //[1,2,3,4,5]
console.log(c2.play); //[1,2,3,4]
console.log(c1.getName); //underfind
组合继承(组合原型链继承和构造函数继承)
特点:可以继承父类原型上的属性,可以传参,可以复用。并且每个新实例引入的构造函数属性都是私有的
缺点:调用了两次父类构造函数(耗内存
// 组合继承
function Parent() {
this.name = "parent";
this.play = [1, 2, 3];
}
Parent.prototype.getName = function () {
return this.name;
};
function Child() {
//第二次调用父类构造函数
Parent.call(this);
this.type = "child";
}
//第一次调用父类构造函数
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let c1 = new Child();
let c2 = new Child();
c1.play.push(4);
console.log(c1.play); //[1,2,3,4]
console.log(c2.play); //[1,2,3]
原型式继承
特点:借助Object.create()方法实现普通对象的继承
缺点:Object.create方法实现的是浅拷贝,多个实例的引用类型属性指向相同的内存,存在篡改的可能
// 原型式继承;
let parent = {
name: "parent",
play: [1, 2, 3],
getName: function () {
return this.name;
},
};
let child1 = Object.create(parent);
child1.name = "xiaoyang";
child1.play.push(4);
let child2 = Object.create(parent);
child2.play.push(5);
console.log(child1.name); //xiaoyang
console.log(child1.getName == parent.getName);
console.log(child1.getName()); //xiaoyang
console.log(child1.play); //[1,2,3,4,5]
console.log(child2.play); //[1,2,3,4,5]
寄生式继承
特点:在原型式继承外面套了一层函数
缺点:与原型式继承一样
//寄生式继承
let parent = {
name: "parent",
play: [1, 2, 3, 4],
getName: function () {
return this.name;
},
};
function clone(orginal) {
let clone = Object.create(orginal);
clone.getPlay = function () {
return this.play;
};
return clone;
}
let child = clone(parent);
console.log(child.name); //parent
console.log(child.play); //[1,2,3,4]
寄生组合式继承(最优)
特点:也是借助Object.create()方法实现普通对象的继承,在此基础上进行改造
//寄生组合式继承
function clone(parent, child) {
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
}
function Parent() {
this.name = "parent";
this.play = [1, 2, 3, 4];
}
Parent.prototype.getName = function () {
return this.name;
};
function Child() {
Parent.call(this);
this.friend = "xiaoyang";
}
clone(Parent, Child);
Child.prototype.getFriend = function () {
return this.friend;
};
let c1 = new Child();
let c2 = new Child();
c1.play.push(5);
console.log(c1.play); //[1,2,3,4,5]
console.log(c2.play); //[1,2,3,4]
console.log(c1.getName()); //parent
console.log(c1.getFriend()); //xiaoyang