Reason behind this self invoking anonymous function variant(这种自调用匿名函数变体背后的原因)
问题描述
在查看 github 上的 code 时,我发现了以下内容:
While looking at code on github, I found the following:
(function() {
}).call(this);
这显然是一个自调用匿名函数.但是为什么会这样写呢?我习惯于看到规范的变体 (function() {})().
This is clearly a self invoking anonymous function. But why is it written this way? I'm used to seeing the canonical variant (function() {})().
将 .call(this) 用于自调用匿名函数有什么特别的优势吗?
Is there any particular advantage to using .call(this) for a self invoking anonymous function?
看起来一些 commonjs 环境将 this 设置为模块顶层的非全局值.哪些,以及他们将 this 设置为您可能想要保留的内容?
It looks like some commonjs environments set this to a non-global value at the top level of a module. Which ones, and what do they set this to that you might want to preserve?
推荐答案
.call(this) (实际上只是 () 直到我改变它)确保你的顶级级别 this 通过严格模式保持一致,--bare 选项和/或运行环境(顶级 this 不指向全局对象).
.call(this) (was actually just () until I changed it) ensures your top level this to be consistent through strict mode, --bare option and/or the running environment (where top level this doesn't point to global object).
这篇关于这种自调用匿名函数变体背后的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这种自调用匿名函数变体背后的原因
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
