zoukankan      html  css  js  c++  java
  • 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等价。

  • 相关阅读:
    转:验证日期的正则表达式比较全面地验证
    IIS应用地址池监控
    Net预编译 真的好用与否
    关键字检索,找到所有数据
    vue 文件上传自定义实现
    docker 基础(一)
    input表单中嵌入百度地图
    linux系统光盘开机自动挂载-配置本地yum源
    linux学习笔记基础篇(一)
    构建apache web 服务器
  • 原文地址:https://www.cnblogs.com/ycherry/p/10862770.html
Copyright © 2011-2022 走看看