原型链继承
继承的实现
//继承实现:将子类的原型指向父类的实例
Child.prototype = new Parent();
Child.prototype.constructor = Child;
缺点
子类实例修改属性,会相互影响
代码
function Parent() {
this.name = 'parent';
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() {
}
//继承实现:将子类的原型指向父类的实例
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child();
var child2 = new Child();
console.log(child1.colors); //["red", "blue", "green"]
child1.getName(); //parent
child2.getName(); //parent
child1.colors.push('black');
//缺点:修改属性会相互影响
console.log(child1.colors); //["red", "blue", "green", "black"]
console.log(child2.colors); //["red", "blue", "green", "black"]
构造函数继承
继承的实现
//缺点:不能继承父类原型
function Child() {
//继承的实现:调用父类构造函数,继承父类属性
Parent.call(this);
}
缺点
只能继承父类的属性,不能继承父类原型
组合继承
继承实现
//缺点:调用两次父类函数,函数开销大
function Child() {
//继承的实现:调用父类构造函数,继承父类属性
Parent.call(this);
}
//继承的实现: 继承父类原型
Child.prototype = new Parent();
Child.prototype.constructor = Child;
缺点
调用两次父类构造函数,开销较大
代码
//缺点:调用两次父类函数,函数开销大
function Child() {
//继承的实现:调用父类构造函数,继承父类属性
Parent.call(this);
}
//继承的实现: 继承父类原型
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child();
var child2 = new Child();
console.log(child1.colors); //["red", "blue", "green"]
child1.getName(); //parent
child2.getName(); //parent
child1.colors.push('black');
//优点:修改属性不会相互影响
console.log(child1.colors); //["red", "blue", "green", "black"]
console.log(child2.colors); //["red", "blue", "green"]
寄生组合继承
继承实现
在组合继承的基础上,通过Object.create(父类原型)
设置子类的原型,减少调用父类构造函数的开销
//继承的实现:将子类的原型指向父类的实例
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
代码
//4.寄生组合继承
function Parent() {
this.name = 'parent';
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child() {
//继承的实现:调用父类构造函数,继承父类属性
Parent.call(this);
}
//继承的实现:将子类的原型指向父类的实例
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var child1 = new Child();
var child2 = new Child();
console.log(child1.colors); //["red", "blue", "green"]
child1.getName(); //parent
child2.getName(); //parent
child1.colors.push('black');
console.log(child1.colors); //["red", "blue", "green", "black"]
console.log(child2.colors); //["red", "blue", "green"]
class继承
class Parent {
constructor() {
this.name = 'parent';
this.colors = ['red', 'blue', 'green'];
}
getName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor() {
super();
}
}
var child1 = new Child();
var child2 = new Child();
console.log(child1.colors); //["red", "blue", "green"]
child1.getName(); //parent
child2.getName(); //parent
child1.colors.push('black');
console.log(child1.colors); //["red", "blue", "green", "black"]
console.log(child2.colors); //["red", "blue", "green"]