简体   繁体   English

或JavaScript对象声明的符号

[英]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: 这真的意味着:

  1. Evaluate the subexpresson to the left. 评估左侧的子表达式。
  2. If that value, when coerced to boolean, is true , then that subexpression's value ( before coercion to boolean) is the value of the || 如果该值在强制转换为布尔值时为true ,那么该子表达式的值( 强制转换为布尔值之前 )是||的值。 expression 表达
  3. Else evaluate the right-hand subexpression and yield its value as the value of the || 否则评估右侧子表达式并将其值作为||的值 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM