Bug Bounties

Why does Babel use Reflect.construct when transpiling ES6 classes into ES5?

For the sake of old browser support, we all use BabelJS to transpile ES6 into ES5. When Babel compiles a class that extends another class, there is a part of compiled code that looks like this: ```js function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } ``` I know the `_createSuper` function is meant to create a function wrapping the process of calling the superclass, which binds `this` as subclass's receiver, so that the subclass can inherit its superclass's properties. To fulfil this purpose, what we need to do is only let `result = Super.apply(this, arguments)`. But the code checks if the environment supports `Reflect` and uses `Reflect.construct` preferentially. I actually don't know why we need `result = Reflect.construct(Super, arguments, NewTarget)` and what it does. Can someone explain it in detail?