前端JS进阶二(ES6-Class语法)

Class和普通构造函数有何区别

前端会使用ES6中的Class来代替JS中的构造函数

JS 构造函数
  function MathHandle(x,y){  //构造函数
    this.x = x;
    this.y = y;
  }
  MathHandle.prototype.add = function(){ //原型的拓展
    return this.x + this.y;
  };

  var m = new MathHandle(1,2);  //实例化构造函数
  console.log(m.add)
Class 语法
  class MathHandle {
      constructor(x, y) {  //构造器
           this.x = x
           this.y = y
      }
      add() {
          return this.x + this.y
      }
  }

  const m = new MathHandle(1, 2)
  console.log(m.add())
语法糖

两种语法的本质是一样的,只是两种格式不同。

  class MathHandle{
    //.......
  }
  typeof MathHandle   //'function'
  //class MathHandle的本质是function
  MathHandle === MathHandle.prototype.constructor  //true
  m.__proto__ === MathHandle.prototype  //true  实例的隐式原型等于构造函数的显示原型
继承 - JS
  function Animal(){
    this.name = name
    this.eat = function(){
      console.log('eat')
    }
  }

  function Dog(){
    this.bark = function(){
      console.log('bark')
    }
  }

Dog.prototype = new Animal()  //绑定原型 实现继承
var hasiqi = new Dog()
hasiqi.bark()
hasiqi.eat()
继承 - Class
  class Animal{
    constructor(name){
      this.name = name
    }
    eat(){
      console.log('eat')
    }
  }
  
  class Dog extends Animal{
    constructor(name){
      super(name)  //将name传到Animal的constructor构造器中去
      this.name = name
    }
    say(){
      console.log('say')
    }
  }

  const dog= new Dog('哈士奇')
  dog.say()
  dog.eat()

总结

  • Class在语法上更加贴近面向对象的写法
  • Class在实现继承更加易读、易理解
  • 更易于写java等后端语言的使用
  • Class本质是语法糖,还是使用prototype的继承方式
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,958评论 1 45
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,431评论 0 3
  • 继承6种套餐 参照红皮书,JS继承一共6种 1.原型链继承 核心思想:子类的原型指向父类的一个实例 Son.pro...
    灯不梨喵阅读 3,207评论 1 2
  • 我大概也许半年后大概也许过了术语关,于是开始了惊心动魄的学习过程,首先自然就是鼎鼎大名的《伤寒论》,这本书一直会贯...
    袁天罡是我祖师爷阅读 337评论 0 2
  • 【0209读书感悟】 书名:刻意学习 作者:Scalers 金句:愿意付费的人,成长的更快。 分享: 该花钱...
    巳岚阅读 143评论 0 0