ES5
function Human(name){
this.name = name
}
Human.prototype.run = function(){
console.log('我叫' + this.name + ',我在跑')
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('糊你熊脸')
}
var man = new Man('ff')
ES6
class Human{
constructor(name){
this.name = name
}
run(){
console.log('我叫' + this.name + ',我在跑')
return undefined
}
}
class Man extends Human{
constructor(name){
super(name)
this.gender = '男'
}
fight(){
console.log('糊你熊脸')
}
}
var man = new Man('ff')
两种方法都能实现继承,本质上ES6继承是ES5继承的语法糖,会更简单些,但是假如要添加一个非函数的属性,比如“种族:人类”。
那么用 ES5 的方法会更方便操作,可以直接添加:
Human.prototype.种族 = ‘人类’
在 ES6 中只能用一种变通的方法来实现:
class Human{
constructor(name){
this.name = name
}
run(){
console.log('我叫' + this.name + ',我在跑')
return undefined
}
get 种族(){
return '人类'
}
}