类的声明
// 类的声明
function Animal(){
this.name='dog'
}
// ES6中类的声明
class Animal2{
constructor(){ // 构造函数
this.name='pig'
}
}
// 实例化
console.log(new Animal(),new Animal2())
继承的方式
借助构造函数实现继承
缺点:父级构造函数原型上的方法,只实现部分继承
function Parent1(){
this.name='parent1'
}
function Child1(){
Parent1.call(this) //将父级构造函数的this指向子构造函数的实例上
this.type='child1'
}
console.log(new Child1())
//=>Child1 {name: "parent1", type: "child1"}
name: "parent1"
type: "child1"
__proto__:
constructor: ƒ Child1()
__proto__: Object
借助原型链实现继承
缺点:共用原型链中的原型对象
function Parent2(){
this.name='parent2'
this.play=[1,2]
}
function Child2(){
this.type='child2'
}
Child2.prototype=new Parent2()
console.log(new Child2())
var s1=new Child2()
var s2=new Child2()
s1.play.push(777)
console.log(s1.play) //=>[1, 2, 777]
console.log(s2.play) //=>[1, 2, 777]
组合方式
缺点:父类执行了两次,子类直接继承父类的实例,没有自己的constructor
function Parent3(){
this.name='parent3'
this.play=[1,2]
}
function Child3(){
Parent3.call(this)
this.type='child3'
}
Child3.prototyp=new Parent3()
var s3=new Child3()
var s4=new Child3()
s3.play.push('777')
console.log(s3) //=>Child3 {name: "parent3", play: Array(3), type: "child3"}
console.log(s4) //=>Child3 {name: "parent3", play: Array(2), type: "child3"}
console.log(s3.constructor) //=>Child3(){Parent3.call(this) this.type='child3'}
组合继承优化
缺点:仍存在组合继承的问题二,子类直接继承父类的实例,没有自己的constructor
function Parent4(){
this.name='parent4'
this.play=[1,2]
}
function Child4(){
Parent4.call(this)
this.type='child4'
}
Child4.prototype=Parent4.prototype
var s5=new Child4()
var s6=new Child4()
console.log(s5) //=>Child4 {name: "parent4", play: Array(2), type: "child4"}
console.log(s6) //=>Child4 {name: "parent4", play: Array(2), type: "child4"}
console.log(s5 instanceof Child4,s5 instanceof Parent4) //=>true,true
console.log(s5.constructor) //=>Parent4(){this.name='parent4' this.play=[1,2]}
组合继承完美写法
function Parent5(){
this.name='parent5'
this.play=[1,2]
}
function Child5(){
Parent5.call(this)
this.type='child5'
}
Child5.prototype=Object.create(Parent5.prototype)
// 进行覆盖,虽然隔离但是仍有作用域
Child5.prototype.constructor=Child5
var s7=new Child5()
var s8=new Child5()
console.log(s7 instanceof Child5,s7 instanceof Parent5) //=>true,true
console.log(s7.constructor) //=>Child5(){Parent5.call(this) this.type='child5'}