美文网首页
JS 继承的两种写法

JS 继承的两种写法

作者: sxfshdf | 来源:发表于2018-12-18 20:52 被阅读0次

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 '人类'
 }
}

相关文章

  • JS 继承的两种写法

    ES5 ES6 两种方法都能实现继承,本质上ES6继承是ES5继承的语法糖,会更简单些,但是假如要添加一个非函数的...

  • JS中继承的写法

    继承的两种写法 i.Prototype 写法 ii.Class写法 iii.两种方法的区别 两种方法都能实现继承,...

  • class-继承(es6)

    继承-JS 继承-class class-总结 Class 在语法上更加贴合面向对象的写法Class 实现继承更加...

  • JS继承

    JS中的继承 许多OO语言都支持两种继承方式:接口继承和实现继承; 因为JS中没有类和接口的概念 , 所以JS不支...

  • JS中继承的写法

    继承是类和类之间的关系,继承使得子类别具有父类别的属性和方法。 js里常用的如下两种继承方式: 原型链继承(对象间...

  • JS中继承的写法

    继承是面向对象编程很重要的一个方面,让子类继承父类的某些属性和方法,是非常常见的需求。 prototype写法 假...

  • JS 中继承的写法

    下面做一个测试题: 写出一个构造函数 Animal 输入为空 输出为一个新对象,该对象的共有属性为 {行动: fu...

  • JS 中继承的写法

    什么是继承 继承(英语:inheritance)是面向对象软件技术当中的一个概念。如果一个类别B“继承自”另一个类...

  • JS 中继承的写法

    es5: es6: class 在原型上声明一个不是函数的属性:es5:Human.prototype.race ...

  • #js继承

    js继承的概念 js里常用的如下两种继承方式: 原型链继承(对象间的继承)类式继承(构造函数间的继承) 类式继承是...

网友评论

      本文标题:JS 继承的两种写法

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