父类函数
function Father(param){
this.age = param || 18
}
Father.prototype.say = function () {
console.log('father say')
}
1:原型链继承(不推荐)
function Child () {}
Child.prototype = new Father()
// 缺点 :
1 无法向父类构造函数传参;
2 父类的所有属性被共享
2:构造函数继承(不推荐)
function Child(name){
Father.call(this)
this.name = name
}
var c = new Child('c')
c.name // 'c'
c.age // 18
c instanceof Child // true
c instanceof Father // false
// 优点
1 可以给父类传参
2 避免了共享属性
// 缺点
1 子类的实例,不是父类的实例
2 方法都在构造函数中创建,每次创建实例都会创建一次方法
3:组合继承(推荐)
function Child(age, name) {
Father.call(this, age)
this.name = name
}
Child.prototype = new Father()
Child.prototype.constructor = Child
let jon = new Child(18, 'jon')
jon.age // 18
jon.name // jon
let flash = new Child(22, 'flash')
flash.age // 22
flash.name // flash
jon.age // 18
jon instanceof Father// true
jon instanceof Child// true
flash instanceof Father// true
flash instanceof Child// true
4:寄生组合继承(最佳)
5:ES6 extends (最佳)