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等价。

  • 相关阅读:
    sql语句开发使用---update
    获取弹出框的句柄,关闭弹出框
    水晶报表使用,解决相同数据库不同服务器使用同一个水晶报表模板问题?
    第一章 什么是SQL Server Integration Services (ssis) 系统。
    在 win 10 中使用sql 2012 附加低版本数据失败的解决办法。
    窗体间传值 委托应用
    有点小激动
    Adam
    SVN Unable to connect to a repository at URL问题解决
    C#基础---IComparable用法,实现List<T>.sort()排序
  • 原文地址:https://www.cnblogs.com/ycherry/p/10862770.html
Copyright © 2011-2022 走看看