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