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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:03:59  来源:igfitidea点击:

What does "var app = app || {};" do?

javascriptbackbone.js

提问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 appto an empty object if it is not already defined.

如果变量app尚未定义,它会将变量定义为一个空对象。

This works because being undefined evaluates to falsein 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 apphas 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 ORoperator in JavaScriptdoes not necessarily yield a boolean. If the left-hand side of the expression yields falsethen the assignment takes the right-hand side of the expression.

OR运营商JavaScript并不一定产生boolean。如果表达式的左侧产生,false则赋值采用表达式的右侧。

回答by Jakob

If appis already defined, the it does nothing. If appis not defined, then it's equivalent to var app = {};

如果app已经定义,则它什么都不做。如果app没有定义,那么它等价于var app = {};