问题
I've seen namespaces in JavaScript defined as:
var AppSpace = AppSpace || {};
and/or
var namespace = {};
Can anyone tell me:
- What's the difference?
- What's || used for in the first example?
- Why, in the first example, is
AppSpace
used twice? - 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