1、随着前端发展越来越快,ES6(ECMAScript 6)于 2015 年 6 月正式发布,成为前端开发者的常用写法;
2、ES6最常用语法有:let、const、class、extends、Symbol、Proxy、set和map数据结构等等;
3、在此不对语法做详细解析,想要了解的可以参考阮一峰老师的电子书(http://es6.ruanyifeng.com/);
4、本文主要围绕组件中最常用的class和extends转换成ES5语法做简析;
5、进入Babel的官网(https://www.babeljs.cn/),点击“试用”;
6、将class与extends转换成ES5语法代码如下;
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function B() {
}
var A = function (_B) {
_inherits(A, _B);
function A() {
_classCallCheck(this, A);
return _possibleConstructorReturn(this, (A.__proto__ || Object.getPrototypeOf(A)).apply(this, arguments));
}
return A;
}(B);
7、提炼出以下几点;
7.1 严格模式;
7.2 class A extends B {} 实际上就是创建了一个A方法用B方法来调用;
7.3 在A方法内部,调用了_inherits(A, _B)和返回了名为A的方法;
7.4 _inherits(A, _B)方法解析:1._B必须是一个函数(function),否则抛错;2.将_B的原型(prototype)复制给A的原型(prototype),并将A原型的构造函数指向A自己,即A可以继承_B上所有的属性和方法;3.将A的原型指向_B。
7.5 再看内部名为A的方法,调了_classCallCheck(this, A)和返回了_possibleConstructorReturn;classCallCheck(this, A)方法是调用A方法传入的参数必须是A类型的,否则抛错。_possibleConstructorReturn方法是A方法传入的参数如果是对象或者是方法则返回这个对象或者方法,如果不是,则返回A的实例。
7.6 流程图如下;