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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With