Leo*_*ang 6 javascript ecmascript-6
一些ES6功能非常容易填充:
if(!Array.prototype.find){
Array.prototype.find=...
}
Run Code Online (Sandbox Code Playgroud)
你会怎么填充new.target?它在不受支持的浏览器中使用时会触发语法错误.try/catch不起作用,因为它是语法错误.我不必使用new.target,我只是好奇.
正如Jaromanda评论的那样,您无法填充新的语法,但您现在可以轻松解决一些 new.target用例问题
看一下new.target文档,你会看到一些可以用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"
Run Code Online (Sandbox Code Playgroud)
无
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"
Run Code Online (Sandbox Code Playgroud)
同 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"
Run Code Online (Sandbox Code Playgroud)
无
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"
Run Code Online (Sandbox Code Playgroud)
希望这有所帮助