模块化 - Javascript是否需要私有变量?
迷茫
迷茫 2017-04-10 14:27:35
[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在中实现私有变量有什么看法?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
阿神

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号