javascript - Babel's problem with inheriting predefined class conversions
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-19 10:30:16
0
1
543

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": []
}

ES6code before compilation:

//类的定义
class ROUTE extends Array{

    constructor(position){
        super();
        this.push({
            position: (position || [0,0,0])
        })
    }

    push(geometry){
        ...//业务相关代码
    }
}

ES5code 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"
  }
曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(1)
我想大声告诉你

Partial support
Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date, Array and Error cannot be due to ES5 engine limitations.

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...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template