Javascript namespaces that use ||

别等时光非礼了梦想. 提交于 2019-12-10 18:35:16

问题


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:


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


来源:https://stackoverflow.com/questions/13439545/javascript-namespaces-that-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!