继承是指一个对象直接使用另一对象的属性和方法。
ES5:
function Human(name){
this.name = name
}
Human.prototype.run = function(){
console.log(this.name+'跑步 ing')
return undefined
}
function Man(name){
Human.call(this,name)
this.gender = '男'
}
var f = function(){}
f.prototype = Human.prototype
Man.prototype = new f()
Man.prototype.fight = function(){
console.log('打架 ing')
}
ES6:
class Human{
constructor(name){
this.name = name
}
run(){
console.log(this.name+'跑步 ing')
return undefined
}
}
class Man extend Human{
constructor(name){
super(name)
this.gender = '男'
}
fight(){
console.log('打架 ing')
}
}
优劣对比:
ES5 继承的写法,从原型链的角度来看更易于理解,但写法上比 ES6 的继承稍有复杂。
网友评论