[英]Or symbol for JavaScript object declaration
I just started to read some JavaScript project. 我刚刚开始阅读一些JavaScript项目。 Most of the .js file to start with have an object declared as the following:
大多数开头的.js文件都有一个声明如下的对象:
window.Example || {
bleh: "123";
blah: "ref"
}
What does the ||
什么是
||
symbol do here? 符号在这做?
Objects in Javascript are truthy, so that expression evaluates to either window.Example
or the default object if window.Example
is falsy (or undefined). Javascript中的对象是真实的,因此表达式计算为
window.Example
或默认对象,如果window.Example
是falsy(或undefined)。 Example: 例:
var x = window.Example || {foo: 'bar'};
// x = {foo: 'bar'}, since window.Example is undefined
window.Example = {test: 1};
var y = window.Example || {foo: 'bar'};
// y = {test: 1}, since window.Example is truthy (all objects are truthy)
Read this article for a good explanation on truthy/falsy and short-circuit evaluation. 阅读这篇文章,以获得关于truthy / falsy和短路评估的详细解释。
The ||
||
operator in JavaScript is like the "or" operator in other C-like languages, but it's distinctly different. 运营商在JavaScript是像 “或”运营商在其他类似C语言,但它是截然不同的。 It really means:
这真的意味着:
true
, then that subexpression's value ( before coercion to boolean) is the value of the ||
true
,那么该子表达式的值( 在强制转换为布尔值之前 )是||
的值。 expression ||
||
的值 expression. Thus it's used idiomatically to initialize something that might already be initialized: 因此,它惯用于初始化可能已经初始化的东西:
var something = window.something || defaultValue;
just means, "check to see if "something" is a property of the window
object with a truthy value, and if it's not, then set it to defaultValue." 只是意味着,“检查”某事物“是否是具有真值的
window
对象的属性,如果不是,则将其设置为defaultValue。”
There's an important bit missing from that code - the variable declaration: 该代码中缺少一点重要的 - 变量声明:
var something = window.Example || {
bleh: "123",
blah: "ref"
}
This roughly translates to "set something
to window.Example
, unless it doesn't exist, then set it to this new object". 这大致转换为“将
something
设置为window.Example
,除非它不存在,否则将其设置为此新对象”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.