为什么命名空间被认为是JavaScript中的不良做法? [英] Why are namespaces considered bad practice in JavaScript?

查看:124
本文介绍了为什么命名空间被认为是JavaScript中的不良做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知命名空间不应该被使用,因为它们污染了全局范围。我想知道什么是替代方案?



当我想定义效用函数和/或常量对于一个网站来说,一个简单的方法是通过命名空间来定义它们,这样对全局范围的损害只能被限制在一个对象上。



如果命名空间是不好的做法,请记住几个问题:


  1. 为什么这个坏习惯?

  2. 这个声明的范围是什么(网页应用/动态网站/静态网站等)?

  3. 有哪些选择?

这个问题是在关于使用extend.js的好处的帖子

解决方案


为什么这是不好的做法?


命名空间本身是坏的,因为这是一个不必要的概念。



拥有属性和方法的对象是可以接受的。有一个类似于命名空间的模块令牌也是可以的,而这意味着你每个文件都有一个模块标记,它包含所有的属性和方法。这与命名空间不同,因为它仅在单个文件中创建/更改,并不作为全局令牌公开。


这个声明的范围是什么(网页应用/动态网站/静态网站等)?


所有ECMAScript,永远不会创建新的全局令牌


有什么选择?


而不是命名空间,你应该喜欢多个文件本地令牌。这意味着每个文件/模块都应该被封装在一个闭包中,你应该可以访问这个闭包中的多个局部变量。



全局变量也是坏的,因为你永远不需要他们。避免全局变量的方式是将所有内容都封装在封装中,并且在加载外部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:

  1. Why is this bad practice?
  2. What's the scope of this declaration (web applications / dynamic websites / static websites etc.)?
  3. What are the alternatives?

This question is a result of a discussion started on a post on the benefits of using 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.)?

All ECMAScript, never create new global tokens

what are the alternatives?

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.

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.

Examples of zero global module loaders

Further reading:

这篇关于为什么命名空间被认为是JavaScript中的不良做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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