为什么命名空间在 JavaScript 中被认为是不好的做法?
有人告诉我不应使用命名空间,因为它们会污染"全局范围.我想知道有什么替代方案?
I've been told namespaces shouldn't be used, as they 'pollute' the global scope. I wonder what are the alternatives?
当我想定义实用函数和/或常量时,例如对于网站来说,一种简单的方法是通过命名空间来定义它们,这样对全局范围的损害仅限于一个对象.
When I want to define utility functions and / or constants e.g. for a website, a simple way to go would be to define them by namespaces, that way the damage to the global scope is restricted to one object only.
如果命名空间是不好的做法,我会想到几个问题:
If namespaces are bad practice, a couple of questions comes to mind:
- 为什么这是不好的做法?
- 此声明的范围是什么(网络应用程序/动态网站/静态网站等)?
- 有哪些替代方案?
这个问题是在 一篇关于使用 extend.js 的好处的帖子.
推荐答案
为什么这是不好的做法?
why is this bad practice?
命名空间本身很糟糕,因为它是一个不必要的概念.
namespaces themself are bad because it's an unnecessary concept.
拥有带有属性和方法的对象是可以接受的.拥有一个类似于命名空间"的模块"令牌也很好,但其含义是每个文件都有一个模块"令牌,其中包含所有属性和方法.这与命名空间"不同,因为它仅在单个文件中创建/更改,并且不作为全局令牌公开.
Having objects with properties and methods is acceptable. It's also fine to have a "module" token which is similar to a "namespace" but instead the meaning is that you have one "module" token per file which contains all your properties and methods. This is different from a "namespace" because it's only created / altered in a single file and isn't exposed as a global token.
此声明的范围是什么(网络应用程序/动态网站/静态网站等)?
what's the scope of this declaration (web applications / dynamic websites / static websites etc.)?
所有 ECMAScript,从不创建新的全局令牌
All ECMAScript, never create new global tokens
有什么选择?
而不是拥有命名空间,您应该支持多个文件本地"令牌.这意味着每个文件/模块"都应该包装在一个闭包中,并且您应该可以访问该闭包内的多个局部变量.
Rather then having namespaces you should favour multiple "file local" tokens. Meaning that each file / "module" should be wrapped in a closure and you should have access to multiple local variables inside this closure.
全局变量也很糟糕,因为您根本不需要它们.避免全局变量的方法是将所有内容包装在闭包中,并在加载外部 javascript 文件时保持智能.
Global variables are also bad because you don't need them, at all, ever. The way you avoid globals is by wrapping everything in closures and being intelligent in how you load external javascript files.
零全局模块加载器示例
- 节点浏览
- webmake
- modul8
进一步阅读:
- 没有全局变量的模块化
- CommonJS 模块
相关文章