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

Some ES6 features are really easy for polyfill:

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

How would you polyfill new.target? It causes a syntax error when used in an unsupported browser. try/catchdoes not work because it is a syntax error. I do not need to use new.target, I am basically just interested.

+4
source share
1 answer

As Jaromanda pointed out, you cannot use the new polyfill syntax, but now you can easily get around some use cases new.target

Taking a look at new.target docs , you will see some examples that can be easily written using es5

from 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"

from 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"

,

+4

Source: https://habr.com/ru/post/1613290/


All Articles