用ES5和ES6实现继承
2019-07-10 本文已影响0人
吴一晏
ES5 prototype实现继承
function Human (name) {
this.name = name
}
Human.prototype.run = function () {}
function Man (name) {
Human.call(this,name) //改变自身属性
this.gender = '男'
}
Man.__proto__ = Human.prototype //实现继承
var f = function () {} //IE不支持上面的写法,需要引入一个空函数
f.prototype = Human.prototype
Man.prototype = new f()
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('糊你一脸')
}
}