1.原型继承
1 | function Animal(){ |
2.借用构造函数
1 | function Parent(name){ |
优点:1、避免了引用类型的属性被实例共享;
2、在子类中可以向父类中传参数;
缺点:1、无法继承原型;
2、每次创建实例时都会调用一次方法
3.组合继承
组合继承就是将原型方法和构造函数方法结合在一起的方法。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21function Parent(name){
this.name = name;
this.age = 10;
}
Parent.prototype.sayName = function(){
console.log(`parent name is ${this.name}`);
}
Parent.prototype.doSomthing = function(){
console.log('parent is doing something')
}
function Child(name){
Parent.call(this,name)
}
Child.prototype = new Parent('father');
Child.prototype.constructor = Child;
Child.prototype.sayName = function(){
console.log(`child's name is ${this.name}`);
}
var child = new Child('child')
child.sayName();//child's name is child
child.doSomthing();//parent is doing something
缺点:组合继承是JS最常用的继承模式,但是在组合继承中,父类会被调用两次,一次在子类构造函数内,一次在子类原型继承父类实例.
4.原型式继承
1 | var ob = {name:'xiaobao',friends:['jie','bao']}; |
缺点:实例会共享引用类型的变量
5.寄生式继承
创建一个仅用于封装过程的函数,在函数内部以某种方式增强对象。1
2
3
4
5
6
7
8
9
10
11
12
13var ob = {
name:'xiaobao',
friends:['xiaojie','xiaowen']
}
function createObj(obj){
var newObj = Object.create(obj);
newObj.sayName = function(){
console.log(this.name);
}
return newObj;
}
var obj = new createObj(ob);
obj.sayName();//'xiaobao'
6.寄生组合式继承
1 | function inhertPrototype(Parent,Child){ |
7.ES6的继承
1、ES6提供了更接近传统语言“类”的写法,引入了Class(类)这个概念,中作为对象的模板;
2、通过Class关键字,可以定义类。Class可以看做只是一个语法糖,它的绝大部分功能,ES5都可以做到。
1 | class Parent{ |
能用ES继承就推荐使用ES6的class继承方式