gpt4 book ai didi

javascript - 如何检测是否使用了 'new'关键字?

转载 作者:行者123 更新时间:2023-11-28 17:58:37 32 4
gpt4 key购买 nike

这是否特别强大(尝试检测“new”关键字是否用于创建对象)?

this.constructor.toString().indexOf('window') === -1

请记住,我不太关心像 IE6/7/8 这样的古老浏览器。

最佳答案

不,它不仅不健壮,而且是错误的。它会在构造函数中的任何位置查找字符 "window",这会给出两个误报(您可以在不使用 "window" 的情况下调用不带 new 的函数) code> 出现在其中任何地方)和漏报(仅仅因为构造函数包含 "window",这并不意味着它不是用 new 调用的)。

在 ES5 及更早版本中,您无法绝对确定 new 是否被使用,但您可以通过以下方式足够接近:

if (this instanceof TheConstructorName) {
// Yes, `new` was probably used
}

...但这可以被击败:

var f = new TheConstructorName(); // Really called with `new`
TheConstructorName.call(f); // Tricks it

如果你使用严格模式,如果有人只是执行TheConstructorName()this将是未定义,但你不能仅仅依赖this未定义,因为有人可以执行 TheConstructorName.call({}) 甚至 var o = {c: TheConstructorName}; o.c();,其中任何一个都将 this 设置为除 undefined 以外的值,即使在严格模式下也是如此。

在 ES2015+ 中,您可以通过查看 new.target 来完全确定。 :

if (new.target) {
// Yes, `new` was used
}

但是,如果您使用 class 语法,则不需要这样做;使用 class 创建的构造函数不能在没有 new 的情况下调用(直接或间接作为 super)。

关于javascript - 如何检测是否使用了 'new'关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44030236/

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