美文网首页
JS中继承的写法

JS中继承的写法

作者: 成成成汤 | 来源:发表于2019-07-15 17:15 被阅读0次

继承的两种写法

i.Prototype 写法

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.prototye = new f()

   Man.prototype.fight = function(){
      console.log('糊你熊脸')
   }
}

ii.Class写法

class Human {
   constructor(name){
      this.name = name
   }
   run(){
      console.log("我叫"+this.name+", 我在跑")
      return undefined
   }
}
class Man extends Human{
   constructor(name){
      supper(name)
      this.gender = '男'
   }
   fight(){
      console.log('糊你熊脸')
   }
}

iii.两种方法的区别

两种方法都能实现继承,本质上ES6继承是ES5继承的语法糖,会更简单些,但是假如要添加一个非函数的属性,比如“种族:人类”。
那么用 ES5 的方法会更方便操作,可以直接添加:

Human.prototype.种族 = '人类'

在 ES6 中只能用一种变通的方法来实现:

class Human {
   constructor(name){
      this.name = name
   }
   run(){
      console.log("我叫"+this.name+", 我在跑")
      return undefined
   }
   get 种族(){
      return '人类'
}
}

相关文章

  • class-继承(es6)

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

  • JS中继承的写法

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

  • JS中继承的写法

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

  • JS 中继承的写法

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

  • JS 中继承的写法

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

  • JS中继承的写法

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

  • JS 中继承的写法

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

  • js组件化开发

    如果不了解js的继承的写法,可以先去看看我之前写的js的子类继承父类文章http://www.jianshu.co...

  • onclick JS的错误写法

    如图报了not defined 的错误 我的错误写法 js中 function a(){} 正确写法 js中 a=...

  • JS 的面向对象

    JS 不是一门面向对象的语言,但是很多情况我们需要面向对象。 一、JS 继承的常用写法。 为什么一上来就写常用写法...

网友评论

      本文标题:JS中继承的写法

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