javascript - 为什么命名空间从 ECMAScript 考虑中移除?

标签 javascript namespaces language-design ecma262

命名空间曾经是 ECMAScript(旧的 ECMAScript 4)的考虑因素,但被取消了。正如 Brendan Eich 在 this message 中所说:

One of the use-cases for namespaces in ES4 was early binding (use namespace intrinsic), both for performance and for programmer comprehension -- no chance of runtime name binding disagreeing with any earlier binding. But early binding in any dynamic code loading scenario like the web requires a prioritization or reservation mechanism to avoid early versus late binding conflicts.

Plus, as some JS implementors have noted with concern, multiple open
namespaces impose runtime cost unless an implementation works
significantly harder.

For these reasons, namespaces and early binding (like packages before
them, this past April) must go.

但我不确定我是否理解所有这些。优先排序或保留机制到底是什么?为什么需要其中任何一个?另外,早期绑定(bind)和命名空间必须齐头并进吗?出于某种原因,我无法解决所涉及的问题。谁能尝试更充实的解释?

此外,为什么 namespace 会增加运行时成本?在我看来,我不禁发现命名空间和使用闭包的函数在概念上几乎没有区别。例如,Yahoo 和 Google 都有 YAHOO 和 google 对象,它们“表现得像” namespace ,因为它们在单个访问点中包含所有公共(public)和私有(private)变量、函数和对象。那么,为什么命名空间在实现上会有如此显着的不同呢?也许我只是对 namespace 到底是什么有误解。

为了赏金,我想知道两件事:

  1. 命名空间是否需要提前绑定(bind)?
  2. 命名空间如何实现 不同于一个对象 私有(private)成员(member)?

最佳答案

如果在函数定义调用该变量后在闭包中声明变量,它仍然使用作用域变量。

function ShowMe() { 
    alert(myVar); //alerts "cool"
}

var myVar = "cool";

这个过程在命名空间方面会变得更加复杂。

除此之外,还有许多命名空间方法以及 expand/applyIf 等可以执行许多相同的功能。例如,ExtJS 中的 namespace(),或 jQuery 中的 $.extend。因此,拥有它可能是件好事,但在语言结构中并不是绝对需要。我认为对 Array 的一些扩展进行形式化以及在 Date 中支持 ISO-8601 日期对我来说更为重要。不必简单地检查每个命名空间层的定义...

window.localization = $.extend(window.localization || {}, {
  ...
});

window.localization.en = $.extend(window.localization.en || {}, {
  ...
});

关于javascript - 为什么命名空间从 ECMAScript 考虑中移除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2390526/

相关文章:

c++ - 如何命名我的新项目的命名空间?

programming-languages - 明确函数可以修改其参数

indentation - 为什么 Julia 不像 Python 那样基于缩进?

javascript - 剪贴板中的粘贴图像功能如何在 Gmail 和 Google Chrome 12+ 中工作?

javascript - WebStorm 6 中的 Closure Compiler 注释,如何使用 Record Types?

javascript - 您如何分发 HTML/Javascript 网络应用程序?

assembly - 玩具编译器的输出语言/格式

javascript - jquery/css 的水平滚动问题

c++ - 当我使用 “using std::cout;” 等时,它仍然被认为是不好的做法吗?

c++ - 存在冲突符号时使用一个或多个命名空间?