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
下命名为car
: car.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:
完全从外部隐藏代码的最佳方法是将其包装到一个块中,这是包装在大括号中的代码的一部分,例如if
或for
块,也可以是这样形成的独立块:
{
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.
但是您需要始终使用块范围内的let
或const
来注意。
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
定义的变量,也无法从外部访问start
和stop
。