javascript “var app = app || {};”是什么意思 做?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16284724/
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
What does "var app = app || {};" do?
提问by rememberlenny
Im looking at some Backbone.js examples and they have var app = app || {};
at the top of all .js files. I understand the literal meaning of this, but what does it do in reference to everything else?
我正在查看一些 Backbone.js 示例,它们var app = app || {};
位于所有 .js 文件的顶部。我明白这个的字面意思,但它对其他一切有什么作用?
Edit: you guys are really really fast.
编辑:你们真的很快。
回答by nullability
It will define the variable app
to an empty object if it is not already defined.
如果变量app
尚未定义,它会将变量定义为一个空对象。
This works because being undefined evaluates to false
in Javascript.
这是有效的,因为未定义false
在 Javascript 中计算为。
If it is defined, it may still be re-defined as an empty object if it has a value which evalutes to false
, such as an empty string.
如果它被定义,如果它有一个评估为 的值false
,例如一个空字符串,它仍然可能被重新定义为一个空对象。
回答by recursive
The ||
operator in javascript will return the first operand if it is "truthy". If not, it will return the second operand. If app
has not been assigned, it will be undefined
, which is "falsey". Thus if it is not defined or is otherwise falsey, an empty object {}
will be assigned to app
.
||
如果它是“真实的”,javascript 中的运算符将返回第一个操作数。如果不是,它将返回第二个操作数。如果app
尚未分配,undefined
则为 ,这是“falsey”。因此,如果它未定义或以其他方式错误,{}
则将向 分配一个空对象app
。
回答by Konstantin Dinev
This means "define app as an empty object if it's not already defined".
这意味着“如果尚未定义 app,则将其定义为空对象”。
The OR
operator in JavaScript
does not necessarily yield a boolean
. If the left-hand side of the expression yields false
then the assignment takes the right-hand side of the expression.
该OR
运营商JavaScript
并不一定产生boolean
。如果表达式的左侧产生,false
则赋值采用表达式的右侧。
回答by Jakob
If app
is already defined, the it does nothing.
If app
is not defined, then it's equivalent to var app = {};
如果app
已经定义,则它什么都不做。如果app
没有定义,那么它等价于var app = {};