gpt4 book ai didi

javascript - 你如何填充 Javascript ES6 `new.target` ?

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:52 26 4
gpt4 key购买 nike

一些 ES6 特性真的很容易 polyfill:

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

你会如何 polyfill new.target?在不受支持的浏览器中使用时会触发语法错误。 try/catch 不起作用,因为它是一个语法错误。我不必使用 new.target,我主要只是好奇。

最佳答案

正如 Jaromanda 评论的那样,您不能 polyfill 新语法,但您现在可以轻松解决一些 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"

希望对您有所帮助

关于javascript - 你如何填充 Javascript ES6 `new.target` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33360253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com