使用||的Javascript名称空间 [英] Javascript namespaces that use ||

查看:90
本文介绍了使用||的Javascript名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到JavaScript中的命名空间定义为:

I've seen namespaces in JavaScript defined as:

var AppSpace = AppSpace || {};

和/或

var namespace = {};

任何人都可以告诉我:


  1. 有什么区别?

  2. 什么是||用于第一个例子?

  3. 为什么,在第一个例子中, AppSpace 使用了两次?

  4. 哪个是首选语法?

  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?


推荐答案

|| 运算符是逻辑或,如果左操作数是真值,则Javascript中返回其左操作数,否则返回其右操作数。第一种语法是首选,因为当您不确定命名空间是否已被定义时,您可以在代码中的多个位置(例如在不同的文件中)重用它:

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"

对比:

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

var AppSpace = {}; // Overwrites Appsauce
console.log(AppSauce.x); // Outputs undefined

这篇关于使用||的Javascript名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆