Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 441
Leo Jiang Avatar asked Oct 27 '15 05:10

Leo Jiang


People also ask

What are the 5 new features in ES6?

ES6 comes with significant changes to the JavaScript language. It brought several new features like, let and const keyword, rest and spread operators, template literals, classes, modules and many other enhancements to make JavaScript programming easier and more fun.

What are the new introductions in ES6?

ES6 introduced several key features like const, let, arrow functions, template literals, default parameters, and a lot more. Let's take a look at them one by one. Before ES6 we mainly made use of the var keyword whenever we wanted to declare a variable.

Which method returns the new instance created by the target constructor?

construct() method acts like the new operator, but as a function. It is equivalent to calling new target(... args) . It gives also the added option to specify a different prototype.

What does => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


1 Answers

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

like image 137
Mulan Avatar answered Oct 04 '22 02:10

Mulan