此实例的严格模式替代arguments.callee
有一个老技巧(我在 SO 上学到的)可以捕获将构造函数作为函数调用,即忘记 new
关键字。以下内容或类似内容位于顶部的每个构造函数中。
if (!(this instanceof arguments.callee)) {
throw Error("Constructor called as a function");
}
当您需要 "use strict";
时,有哪些替代方案?
能否保留其通用性?或者我们是否必须使用构造函数的名称来代替arguments.callee
?
There's an old trick (that I learned on SO) to catch calling a constructor as a function, i.e. forgetting the new
keyword. The following, or something like, it goes in each constructor at the top.
if (!(this instanceof arguments.callee)) {
throw Error("Constructor called as a function");
}
What are the alternatives when you need to "use strict";
?
Can its generic nature be retained? Or do we have to use the name of the constructor in place of arguments.callee
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
arguments.callee
本身已被弃用,取而代之的是命名函数表达式。虽然我不一定同意这个举动,但事情就是这样进展的。因此,将arguments.callee
替换为函数名是严格模式下的唯一方法,也是非严格模式下的首选方法。arguments.callee
itself is deprecated in favor of named function expressions. Although I don't necessarily agree with this move, it is how things have progressed. As such, replacingarguments.callee
with the function name is the only way in strict mode, and is also the preferred way in non-strict mode.