• ES6:class的定义与继承,从ES5转换成ES6


    1.ES5中class功能的实现:

    var Person5 = function(name, yearOfBirth, job) {
      this.name = name; // 属性的添加
      this.yearOfBirth = yearOfBirth;
      this.job = job;
    }
    
    //添加方法:
    Person5.prototype.calculateAge = function() {
      var age = new Date().getFullYear() - this.yearOfBirth;
      console.log(age);
    }
    
    var john5 = new Person5('John', 1999, 'teacher');

    ES6中class的定义:

    class Person6 {
      constructor(name, yearOfBirth, job) { //通过构造函数添加属性
        this.name = name;
        this.yearOfBirth = yearOfBirth;
        this.job = job;
      }
      calculateAge() { // 添加方法
        var age = new Date().getFullYear() - this.yearOfBirth;
        console.log(age);
      }
    
      static greeting() {
        console.log('Hey there!');
      }
    }
    const john6 = new Person6('John', 1999, 'teacher');

    将john5 和 john6输出:

    从上图可以看出john5和john6是一样的,所以es5和es6的效果是等价的。

    2.继承

    ES5实现继承:

    var Athlete5 = function(name, yearOfBirth, job, olympicGames, medals) {
      Person5.call(this, name, yearOfBirth, job); // 通过call将this绑在Person5上
      this.olympicGames = olympicGames;
      this.medals = medals;
    }
    
    // 手动设置原型链
    Athlete5.prototype = Object.create(Person5.prototype); // 先设置
    Athlete5.prototype.wonMedal = function () { //再加自己的方法
        this.medals++;
        console.log(this.medals);
      }
    var johnAthlete5 = new Athlete5('John', 1990,  'swimmer', 3, 10);
    johnAthlete5.calculateAge();// 继承原型链上的方法
    johnAthlete5.wonMedal();// 自己的方法

    ES6实现继承:

    class Athlete6 extends Person6 {
      constructor(name, yearOfBirth, job, olympicGames, medals) {
        super(name, yearOfBirth, job);
        this.olympicGames = olympicGames;
        this.medals = medals;
      }
    
      wonMedal() {
        this.medals++;
        console.log(this.medals);
      }
    }
    
    const johnAthlete6 = new Athlete6('John', 1990, 'swimmer', 3, 10);
    johnAthlete6.calculateAge();
    johnAthlete6.wonMedal();

    输出johnAthlete5 和johnAthlete6,

    说明johnAthlete5 和johnAthlete6是一样的,ES5和ES6等价。

  • 相关阅读:
    Java中List集合去除重复数据的方法
    ActiveMQ消息中间件Producer和Consumer
    JMS Activemq实战例子demo
    利用正则表达式判断输入内容是否全中文
    纯js的右下角弹窗
    java开源项目
    linux部署jdk-tomcat
    你的主机中的软件中止了一个已建立的连接。
    Centos编译安装 LAMP (apache-2.4.7 + mysql-5.5.35 + php 5.5.8)+ Redis
    在LAMP的生产环境内添加PHP的cURL扩展模块
  • 原文地址:https://www.cnblogs.com/ycherry/p/10862770.html
Copyright © 2020-2023  润新知