zoukankan      html  css  js  c++  java
  • 新得关键字class-ES6

    ES6中,引入了一个新的关键字class,其目的是让定义类更简单:好处就是极大的简化了原型链的代码

    使用函数实现Student的方法:

    function Student(name){

    this.name = name;

    }

    Student.prototype.hello = function(){

    alert(“hello, ” + this.name  + “!”)

    }

    如果用新的class关键字来编写Student,可以这样写:

    class Student{

     constructor(name){

    this.name = name;

    }
    hello(){

    alert(“hello, ” + this.name + “!”)

    }

    }

    相比较以下,class的定义包含了构造函数contructor和定义在原型对象上的函数hello()(注意没有function关键字)这样就避免了Student.prototype.hello = function(){}

    class继承

    用class定义的另一个巨大的好处是继承更方便:

    class PrimaryStudent extends Student{

    constructor(name,grade){

    super(name);

    this.grade = grade;

    }

    myGrade(){

    alert(“I am at grade ” + this.grade );

    }

    }

    注意PrimaryStudent的定义也是class关键字实现的,而extends则表示原型链对象来自Student。子类的构造函数可能与父类不太相同,例如PrimaryStudent需要name和grade两个参数,并且需要通过Super(name)来调用父类的构造函数,否则父类的name属性无法正常的初始化。

    但是需要注意的是:不是所有的主流浏览器都支持ES6的class。如果一定要现在就用上米就需要一个工具把 class代码转换成传统的prototype代码,可事实Babel这个工具

  • 相关阅读:
    Redis服务器配置
    Spark History Server配置使用
    CentOS7.3安装Nginx
    U盘安装CentOS7的最终解决方案
    iconfont_3种引用方式
    div+css 让一个小div在另一个大div里面 垂直居中
    JavaScript数组方法
    addEventListener()和removeEventListener()
    js获取网页高度
    Linux修改命令行样式
  • 原文地址:https://www.cnblogs.com/orange2013/p/8472728.html
Copyright © 2011-2022 走看看