1. 原型链继承:把父类实例放到子类原型上。
function Animal() {
this.kind = '动物';
}
Animal.prototype.eat = function () {
console.log('eat');
}
function Cat() {
this.age = 1;
}
Cat.prototype = new Animal();
var cat = new Cat();
console.log(cat.kind);
cat.eat();
2. 构造函数继承:通过在子类中通过改变this指向复用父类的构造函数来实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
this.age = 18;
}
var child = new Child();
console.log(child.name);
child.sayHello();
3. 组合继承:通过结合原型链继承和构造函数继承来实现继承,在子类构造对象时可以通过call给复用的父类构造函数传参。
function Parent() {
this.name = 'Parent';
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name);
4. 原型式继承:通过创建一个临时的构造函数来实现继承。
function createObj(o) {
function F() {}
F.prototype = o;
return new F();
}
const parent = {
name: 'Parent'
};
const child = createObj(parent);
console.log(child.name);
5. 寄生式继承:在原型式继承的基础上,增强对象,返回一个具有附加属性和方法的对象。
function createObj(o) {
const clone = Object.create(o);
clone.sayHello = function() {
console.log('Hello');
}
return clone;
}
const parent = {
name: 'Parent'
};
const child = createObj(parent);
console.log(child.name);
child.sayHello();
6. 组合寄生式继承:通过借用构造函数继承属性和方法,并利用原型链继承原型上的方法。
function Parent() {
this.name = 'Parent';
}
function Child() {
Parent.call(this);
}
function inheritPrototype(child, parent) {
const o = Object.create(parent.prototype);
o.constructor = child;
child.prototype = o;
}
inheritPrototype(Child, Parent);
const child = new Child();
console.log(child.name);