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

  • 相关阅读:
    2015年第5本(英文第4本):Death on the Nile尼罗河上的惨案
    2015年第4本(英文第3本):Godfather教父
    2015年第3本(英文第2本):Daughter of Deceit
    2015年第2本(英文第1本):《The Practice of Programming》
    2015年第1本读书行动笔记:《把你的英语用起来》
    GTD桌面2.0
    独立博客开张!有关读书、GTD和IT方面的内容将发布在新网站上
    2015计划
    Swift
    Swift
  • 原文地址:https://www.cnblogs.com/ycherry/p/10862770.html
Copyright © 2011-2022 走看看