“var FOO = FOO || 是什么?{}"(为该变量分配一个变量或一个空对象)在Javascript中是什么意思?

What does quot;var FOO = FOO || {}quot; (assign a variable or an empty object to that variable) mean in Javascript?(“var FOO = FOO || 是什么?{}(为该变量分配一个变量或一个空对象)在Javascript中是什么意思?)

本文介绍了“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?

推荐答案

你对意图的猜测||{} 非常接近.

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

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 = {
}

两者共享相同的命名空间,然后无论加载两个文件的顺序如何,您仍然可以在 func1func2 中正确定义code>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 || 是什么?{}"(为该变量分配一个变量或一个空对象)在Javascript中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:“var FOO = FOO || 是什么?{}"(为该变量分配一个变量或一个空对象)在Javascript中是什么意思?

基础教程推荐