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

  • 相关阅读:
    开发Django项目01
    本地安装python2.x和python3.x双版本之后怎么使用pip
    python3.x并发编程
    centos6.8安装JDK1.8教程
    yum安装MySQL指定版本
    python爬虫爬取get请求的页面数据代码样例
    python网络爬虫学习笔记
    python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
    CentOS7.5安装python-pip报Error: Nothing to do解决方法
    文件操作
  • 原文地址:https://www.cnblogs.com/orange2013/p/8472728.html
Copyright © 2011-2022 走看看