I used ES6 to write a class that inherits Array and overridden the push method. However, after converting it to ES5 using babel, I found that the method called is still the original push method:
.babelrc:
:
{
"presets": [
"es2015",
"react",
"stage-3"
],
"plugins": []
}
ES6
code before compilation:
//类的定义
class ROUTE extends Array{
constructor(position){
super();
this.push({
position: (position || [0,0,0])
})
}
push(geometry){
...//业务相关代码
}
}
ES5
code compiled by babel:
//先是几个工具方法
var _createClass=function...
var _get=function...
function _classCallCheck...
function _possibleConstructorReturn...
function _inherits...
//类的定义
var ROUTE = function (_Array) {
_inherits(ROUTE, _Array);//继承
function ROUTE(position) {
...//类的构造
}
_createClass(ROUTE, [{
key: "push",
value: function push(geometry) {
//业务相关代码,实际上不会执行
}]);
return ROUTE;
}
In fact, when the method of the ROUTE class instance is executed, the business logic code in the _createClass method will not be called at all, but only the push method of Array will be executed, unless the push method is overridden in the constructor.
babel version:
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-3": "^6.24.1"
}
Due to browser engine limitations, Babel does not support subclasses of some built-in classes, such as Date, Array, Error..., so define the required types according to your own needs
Reference: https://babeljs.io/learn-es20...