什么是“var FOO = FOO ||” {}" (在该变量中指定变量或空对象)是指Javascript? [英] What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?

查看:264
本文介绍了什么是“var FOO = FOO ||” {}" (在该变量中指定变量或空对象)是指Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看在线源代码,我在几个源文件的顶部看到了这个。

Looking at an online source code I came across this at the top of several source files.

var FOO = FOO || {};
FOO.Bar = …;

但我不知道 || {} 确实。

我知道 {} 等于 new Object()我认为 || 是用于如果它已经存在则使用其值,否则使用新对象。

I know {} is equal to new Object() and I think the || is for something like "if it already exists use its value else use the new object.

为什么我会在源文件的顶部看到这个?

Why would I see this at the top of a source file?

推荐答案

您对 || {} 意图的猜测非常接近。

Your guess as to the intent of || {} is pretty close.

此特定模式何时在文件顶部看到用于创建命名空间,即一个命名对象,在该对象下可以创建函数和变量而不会过度污染全局对象。

This particular pattern when seen at the top of files is used to create a namespace, i.e. a named object under which functions and variables can be created without unduly polluting the global object.

为什么使用它的原因是,如果你有两个(或更多)文件:

The reason why it's used is so that if you have two (or more) files:

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func1 = {
}

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func2 = {
}

其中两个文件的加载顺序无关紧要,你仍然得到 func1 func2 正确定义在 MY_NAMESPACE 对象中。

both of which share the same namespace it then doesn't matter in which order the two files are loaded, you still get func1 and func2 correctly defined within the MY_NAMESPACE object correctly.

加载的第一个文件将创建初始 MY_NAMESPACE 对象,任何后续加载的文件将扩充对象。

The first file loaded will create the initial MY_NAMESPACE object, and any subsequently loaded file will augment the object.

有用的是,这也允许异步加载共享相同命名空间的脚本,这可以改善页面加载时间。如果< script> 标记设置了 defer 属性,则无法知道它们将以何种顺序出现解释,如上所述,这也解决了这个问题。

Usefully, this also allows asynchronous loading of scripts that share the same namespace which can improve page loading times. If the <script> tags have the defer attribute set you can't know in which order they'll be interpreted, so as described above this fixes that problem too.

这篇关于什么是“var FOO = FOO ||” {}&QUOT; (在该变量中指定变量或空对象)是指Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆