Javascript是否需要私有变量?


总所周知的是, js 在目前流行的标准中还不支持私有变量。我在阅读一篇讲 js 模块化 很不错的文章《 JavaScript Module Pattern: In-Depth 》时,看到一则谴责作者所说的模块化以及大量运用私有变量违反 js 设计初衷的留言,留言如下:

Comment by steida — March 15, 2010
Module pattern is useless JavaScript mannerism junk. It’s simple product of misunderstanding of JavaScript . Hiding properties and methods in anonymous function does not make sense, except two reasons:
1). I need another variable, and no scope pollution. It’s useful for jQuery- (function($) {})(jQuery), for instance.
2). micro optimization, rarely useful, and only just because Internet Explorer.
Anybody who thinks “private in JavaScript is nice” suffer from false illusion of “safe code” . There is no such thing in dynamic language which JavaScript really is.
If you want method or property as “private”, just mark it in documentation, or use underscore prefix (google closure uses it even as suffix). It’s enough to tell our code readers: “Do not call or use this, and do not except that this “private” property will work forever.
From: http://ajaxian.com

其实我目前的想法跟这位评论者 steida 有些相似,因为我觉得
1. 那些可能对安全性有要求的操作就不应该放在前端做。
2. 私有变量的确可以提供有效的抽象层次,像 js 中一直有私有成员用的变量名用下划线开头。我认为这样足够了,而不需要用闭包来专门做出真的私有变量。

各位对 js 在中实现私有变量有什么看法?

模块化 私有变量 JavaScript

月之艮手空 10 years, 9 months ago

我是下划线/POJO党。闭包私有变量不仅如题主所说无法提供所谓的安全,在断点调试的时候更是噩梦。

很多编程pattern的问题是:先假设别的程序员都是傻子或者恶棍,然后试图写出针对性的防御性代码。这是病,得治。防御性代码应当是“如果事情变糟糕了,那么就崩溃”,而不是“禁止你买菜刀,防止你砍人”

sevvie answered 10 years, 9 months ago

Your Answer