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这个工具

  • 相关阅读:
    hibernate各种状态
    Persistence createEntityManagerFactory方法使用
    JS数组学习笔记
    ES6笔记之参数默认值(译)
    JS是按值传递还是按引用传递?
    linux awk命令详解
    Linux Shell笔记之sed
    类似微信红包随机分配js方法
    ionic tabs隐藏完美解决
    mustache 获取json数据内数组对象指定元素的方法
  • 原文地址:https://www.cnblogs.com/orange2013/p/8472728.html
Copyright © 2011-2022 走看看