javascriptecmascript-6

How do you polyfill Javascript ES6 `new.target`?


Some ES6 features are really easy to polyfill:

if(!Array.prototype.find){
  Array.prototype.find=...
}

How would you polyfill new.target? It triggers a syntax error when it's used in an unsupported browser. try/catch doesn't work because it's a syntax error. I don't have to use new.target, I'm mostly just curious.


Solution

  • As Jaromanda commented, you cannot polyfill new syntax, but you can easily work around some new.target use cases for now

    Taking a look at the new.target docs you'll see some examples that can easily be written with es5

    with new.target

    function Foo() {
      if (!new.target) throw "Foo() must be called with new";
      console.log("Foo instantiated with new");
    }
    
    Foo(); // throws "Foo() must be called with new"
    new Foo(); // logs "Foo instantiated with new"
    

    without

    function Foo() {
      if (!(this instanceof Foo)) throw "Foo() must be called with new";
      console.log("Foo instantiated with new");
    }
    
    Foo(); // throws "Foo() must be called with new"
    new Foo(); // logs "Foo instantiated with new"
    

    with new.target

    class A {
      constructor() {
        console.log(new.target.name);
      }
    }
    
    class B extends A { constructor() { super(); } }
    
    var a = new A(); // logs "A"
    var b = new B(); // logs "B"
    

    without

    class A {
      constructor() {
        // class forces constructor to be called with `new`, so
        // `this` will always be set
        console.log(this.constructor.name);
      }
    }
    
    class B extends A { constructor() { super(); } }
    
    var a = new A(); // logs "A"
    var b = new B(); // logs "B"
    

    Hope this helps a little