JavaScript中的命名空间

What is namespacing?

什么是命名空间?

Namespacing is the act of wrapping a set of entities, variables, functions, objects under a single umbrella term.

名称间隔是在单个总括术语下包装一组实体,变量,函数,对象的行为。

JavaScript has various ways to do that, and seeing the examples will make the concept easier to understand.

JavaScript有多种实现方法,查看示例将使概念更易于理解。

The simplest way to create a namespace is by creating an object literal:

创建名称空间的最简单方法是创建对象文字:

const car = {
  start: () => {
    console.log('start')
  },
  stop: () => {
    console.log('stop')
  }
}

In this way, start and stop are namespaced under car: car.start() and car.stop().

这样,start和stop在car下命名为carcar.start()car.stop()

They are not polluting the global object.

他们没有污染全局对象

Why is this important? One good reason is that nothing can interfere with them.

为什么这很重要? 一个很好的理由是,没有什么可以干扰他们。

The way works also by assigning a variable to an object after it’s created:

该方法还可以通过在创建对象后将变量分配给对象来工作:

const car = {}

car.start = () => {
  console.log('start')
}

car.stop = () => {
  console.log('stop')
}

But they are still accessible from the outside, thanks to the car object reference.

但是由于有了car对象的引用,它们仍然可以从外部访问。

The best way to completely hide code from the outside is to wrap it into a block, which is a part of code wrapped in curly brackets, like an if or for block, but also an independent block formed like this:

完全从外部隐藏代码的最佳方法是将其包装到一个块中,这是包装在大括号中的代码的一部分,例如iffor块,也可以是这样形成的独立块:

{
  const start = () => {
    console.log('start')
  }

  const stop = () => {
    console.log('stop')
  }
}

Those 2 functions are now inaccessible outside of the block.

现在,在块外无法访问这两个功能。

But you need to pay attention at always using let or const, which are block scoped.

但是您需要始终使用块范围内的letconst来注意。

Using var instead would “leak” it outside of the block.

相反,使用var会将其“泄漏”到块外。

To workaround that you can use functions, which is the “old”, pre-let/const way:

要解决此问题,您可以使用函数,这是“旧的”预写/常量方式:

(function() {
  var start = () => {
    console.log('start')
  }

  const stop = () => {
    console.log('stop')
  }
})()

Now start and stop are both inaccessible from the outside, even if start is assigned to a variable defined with var.

现在,即使start分配给使用var定义的变量,也无法从外部访问startstop

翻译自: https://flaviocopes.com/javascript-namespaces/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值