Javascript namespaces that use ||

2019-07-06 00:05发布

I've seen namespaces in JavaScript defined as:

var AppSpace = AppSpace || {};

and/or

var namespace = {};

Can anyone tell me:

  1. What's the difference?
  2. What's || used for in the first example?
  3. Why, in the first example, is AppSpace used twice?
  4. Which is the preferred syntax?

1条回答
别忘想泡老子
2楼-- · 2019-07-06 00:42

The || operator is the logical or which in Javascript returns its left operand if the left operand is truthy, otherwise it returns its right operand. The first syntax is preferable, because you can reuse it it multiple places in your code (say in different files) when you are not sure if the namespace has already been defined or not:

var AppSpace = AppSpace || {}; // AppSauce doesn't exist (falsy) so this is the same as:
                               // var AppSauce = {};
AppSauce.x = "hi";

var AppSpace = AppSpace || {}; // AppSauce does exist (truthy) so this is the same as:
                               // var AppSauce = AppSauce;
console.log(AppSauce.x); // Outputs "hi"

Versus:

var AppSpace = {};
AppSauce.x = "hi";

var AppSpace = {}; // Overwrites Appsauce
console.log(AppSauce.x); // Outputs undefined
查看更多
登录 后发表回答