有些ES6功能非常容易填充:
if(!Array.prototype.find){
Array.prototype.find=...
}
您如何填充new.target
?它在不受支持的浏览器中使用时会触发语法错误。 try/catch
无法正常工作,因为它是语法错误。我不必使用new.target
,我只是好奇。
答案 0 :(得分:5)
正如Jaromanda评论的那样,您无法填充新的语法,但您现在可以轻松解决某些 new.target
用例
看一下new.target docs你会看到一些可以用es5轻松编写的例子
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"
<强>没有强>
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"
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"
<强>没有强>
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"
希望这有点帮助