美文网首页
ES5 与 ES6 ,关于继承的两种写法

ES5 与 ES6 ,关于继承的两种写法

作者: YOJIN | 来源:发表于2018-10-22 19:23 被阅读0次

继承是指一个对象直接使用另一对象的属性和方法。

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 的继承稍有复杂。

相关文章

网友评论

      本文标题:ES5 与 ES6 ,关于继承的两种写法

      本文链接:https://www.haomeiwen.com/subject/mqzgzftx.html