Babel doesn't transpile class extending correctly

Viewed 69

Consider the code below

class Test1 {
    emit() {
        console.log(2)
    }
}

class Test extends Test1 {
    test() {
        console.log(1);
    }
}

const a = new Test();
a.test()

Babel transpiles this code into this

This works perfectly on modern browsers, but it doesn't work on Firefox 43

TypeError: a.test is not a function

What I realized:

  1. Babel transpiles class extending into Reflect.construct (If the platform has Reflect support) or context binding
  2. Reflect.construct(Super, arguments, NewTarget) on Firefox 43 skips prototypes from NewTarget
  3. We can represent this class extending using Reflect.construct in the following form:
const test = {};
test.__proto__ = {
    test() {
        console.log(1);
    },
};

function Super() {
    this.emit = function () {
        console.log(2);
    };
}

function Target() {}

Target.prototype = test.__proto__;
const result = Reflect.construct(Super, [test], Target);
result.test();

Also, I found the code in closure compiler which declares "brokenConstruct".
It refers to this issue

What am I doing wrong? What should I do to resolve this problem?

1 Answers

I realized that It is firefox bug There are comments from core-js/modules/es.reflect.construct polyfill

// `Reflect.construct` method
// https://tc39.es/ecma262/#sec-reflect.construct
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
Related