1. prototype实现继承
function Human(name){
this.name=name
}
Human.prototype.run=function(){
console.log('跑')
}
function Man(name){
Human.call(this,name)
this.gender='男'
}
function f(){}
f.prototype=Human.prototype
Man.prototype=new f()
Man.prototype.constructor=Man
由于IE不支持Man.prototype.proto=Human.prototype这种写法,所以我们通过创建一个空的构造函数,让这个函数的prototype指向Human.prototype,然后让Man.prototype等于这个空函数的实例,实现了原型链的继承。
2. class继承
class Human{
constructor(name){
this.name=name
}
run(){
console.log('跑')
}
}
class Man extends Human{
constructor(name){
super(name)
this.gender='男'
}
fight(){
console.log('打架')
}
}
这种写法的优点是写起来比上面方便,缺点是原型链上的属性值只能是函数。
网友评论