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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6439579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:40:26  来源:igfitidea点击:

What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?

javascriptnamespacesvariable-declarationor-operator

提问by Ricardo Sanchez

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

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

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

But I have no idea what || {}does.

但我不知道有什么|| {}作用。

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.

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

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

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

回答by Alnitak

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 whyit's used is so that if you have two (or more) files:

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

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

and

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

both of which share the same namespace it then doesn't matter in which order the two files are loaded, you still get func1and func2correctly defined within the MY_NAMESPACEobject correctly.

这两个份额的同一个命名空间那么也没关系,其中责令这两个文件被加载,你仍然可以func1func2正确的中定义MY_NAMESPACE正确的对象。

The first file loaded will createthe initial MY_NAMESPACEobject, and any subsequently loaded file will augmentthe object.

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

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

有用的是,这还允许异步加载共享相同命名空间的脚本,从而缩短页面加载时间。如果<script>标签defer设置了属性,您将无法知道它们将被解释的顺序,因此如上所述,这也解决了该问题。

回答by Spudley

var AEROTWIST = AEROTWIST || {};

Basically this line is saying set the AEROTWISTvariable to the value of the AEROTWISTvariable, or set it to an empty object.

基本上这一行是说将AEROTWIST变量设置为变量的值AEROTWIST,或将其设置为空对象。

The double pipe ||is an OR statement, and the second part of the OR is only executed if the first part returns false.

双管道||是一个 OR 语句,只有在第一部分返回 false 时才会执行 OR 的第二部分。

Therefore, if AEROTWISTalready has a value, it will be kept as that value, but if it hasn't been set before, then it will be set as an empty object.

因此,如果AEROTWIST已经有一个值,它会被保留为那个值,但如果之前没有设置过,那么它会被设置为一个空对象。

it's basically the same as saying this:

这与说这个基本相同:

if(!AEROTWIST) {var AEROTWIST={};}

Hope that helps.

希望有帮助。

回答by Benny Neugebauer

There are two main parts that var FOO = FOO || {};covers.

有两个主要部分var FOO = FOO || {};

#1 Preventing overrides

#1 防止覆盖

Imagine you have your code split over multiple files and your co-workers are also working on an Object called FOO. Then it could lead to the case that someone already defined FOOand assigned functionality to it (like a skateboardfunction). Then you would override it, if you were not checking if it already exists.

想象一下,您将代码拆分到多个文件中,而您的同事也在处理一个名为FOO. 然后它可能导致某人已经定义FOO并为其分配了功能(如skateboard函数)的情况。然后你会覆盖它,如果你不检查它是否已经存在。

Problematic case:

问题案例:

// Definition of co-worker "Bart" in "bart.js"
var FOO = {};

FOO.skateboard = function() {
  alert('I like skateboarding!');
};

// Definition of co-worker "Homer" in "homer.js"
var FOO = {};

FOO.donut = function() {
  alert('I like donuts!');
};

In this case the skateboardfunction will be gone if you load the JavaScript file homer.jsafter bart.jsin your HTML because Homer defines a new FOOobject (and thus overrides the existing one from Bart) so it only knows about the donutfunction.

在这种情况下,skateboard如果您在 HTML 中加载 JavaScript 文件homer.js之后bart.js,该函数将消失,因为 Homer 定义了一个新FOO对象(从而覆盖了 Bart 的现有对象),因此它只知道该donut函数。

So you need to use var FOO = FOO || {};which means "FOO will be assigned to FOO (if it exists already) or a new blank object (if FOO does not exist already).

所以你需要使用var FOO = FOO || {};这意味着“FOO 将被分配给 FOO(如果它已经存在)或一个新的空白对象(如果 FOO 已经不存在)。

Solution:

解决方案:

var FOO = FOO || {};

// Definition of co-worker Bart in bart.js
FOO.skateboard = function() {
  alert('I like skateboarding!');
};

// Definition of co-worker Homer in homer.js
var FOO = FOO || {};

FOO.donut = function() {
  alert('I like donuts!');
};

Because Bart and Homer are now checking for the existence of FOObefore they define their methods, you can load bart.jsand homer.jsin any order without overriding each other's methods (if they have different names). So you will always get a FOOobject which has the methods skateboardand donut(Yay!).

因为 Bart 和 Homer 现在FOO在定义他们的方法之前检查存在,所以您可以以任何顺序加载bart.jshomer.js而不覆盖彼此的方法(如果它们具有不同的名称)。所以你总是会得到一个FOO具有方法skateboarddonut(耶!)的对象。

#2 Defining a new object

#2 定义一个新对象

If you've read through the first example then you already now what's the purpose of the || {}.

如果您已经阅读了第一个示例,那么您现在已经知道|| {}.

Because if there is no existing FOOobject then the OR-case will become active and creates a new object, so you can assign functions to it. Like:

因为如果没有现有FOO对象,那么 OR-case 将变为活动状态并创建一个新对象,因此您可以为其分配功能。喜欢:

var FOO = {};

FOO.skateboard = function() {
  alert('I like skateboarding!');
};

回答by alessioalex

Another common use for || is to set a default value for an undefined function parameter also:

|| 的另一种常见用法 也是为未定义的函数参数设置默认值:

function display(a) {
  a = a || 'default'; // here we set the default value of a to be 'default'
  console.log(a);
}

// we call display without providing a parameter
display(); // this will log 'default'
display('test'); // this will log 'test' to the console

The equivalent in other programming usually is:

其他编程中的等价物通常是:

function display(a = 'default') {
  // ...
}

回答by sudipto

If there is no value in AEROTWIST or it is null or undefined the value assigned to the new AEROTWIST will be {} (a blank object)

如果 AEROTWIST 中没有值或者它为空或未定义,则分配给新 AEROTWIST 的值将是 {}(一个空白对象)

回答by pimvdb

The ||operator takes two values:

||操作需要两个值:

a || b

If a is truthy, it will return a. Otherwise, it will return b.

如果 a 为,它将返回a。否则,它将返回b

The falsy values are null, undefined, 0, "", NaNand false. The truthy values are everything else.

该falsy值nullundefined0""NaNfalse。真实值就是其他一切。

So if ahas not been set (is it undefined) it will return b.

因此,如果a尚未设置(是否undefined),它将返回b

回答by ZER0

Notice that in some version of IE this code won't work as expected. Because the var, the variable is redefined andassigned so – if I recall correctly the issue – you'll end up to have always a new object. That should fix the issue:

请注意,在某些版本的 IE 中,此代码无法按预期工作。因为var, 变量被重新定义分配 - 如果我没记错的话 - 你最终将总是拥有一个新对象。这应该可以解决问题:

var AEROTWIST;
AEROTWIST = AEROTWIST || {};