隐私:下划线原型属性还是封装变量?
有些事情一直困扰着我,就像人们意识到了我没有意识到的事情一样。我正在看一个 FOSS 示例(下面进行了简化)...每当我有一个 JavaScript 类时,我更喜欢 Crockford 的变量隐藏方法:
var MyObject = function(handler) {
var x = 1, y = 2;
function myFunction() {
handler(x + y);
}
return {
"myFunction" : myFunction
}
}
不过,有些开发人员使用带下划线的私有属性。
var MyObject = function(handler) {
this._handler = handler;
}
MyObject.prototype._x = 1;
MyObject.prototype._y = 2;
MyObject.prototype.myFunction = function() {
this._handler(this._x + this._y);
}
我理解其中的区别,但冒着听起来很愚蠢的风险:其中一个比另一个有我没有看到的优势吗?我的意思是,我不喜欢“私有”符号;他们不是私人的。我意识到原型链是在对象之间共享的,但它们是私有的。由于无法在运行时更改所有对象的 x 和 y 或节省内存,我不确定原因。
我确信这是有充分理由的,但如果有人愿意进一步启发我,那就太好了。
Something has been bugging me, like people realize something I don't. I'm looking at a FOSS example, (simplified below)... whenever I have a class in JavaScript, I prefer Crockford's variable hiding methodology:
var MyObject = function(handler) {
var x = 1, y = 2;
function myFunction() {
handler(x + y);
}
return {
"myFunction" : myFunction
}
}
Some developers, though, use underscored private properties.
var MyObject = function(handler) {
this._handler = handler;
}
MyObject.prototype._x = 1;
MyObject.prototype._y = 2;
MyObject.prototype.myFunction = function() {
this._handler(this._x + this._y);
}
I understand the difference, but at the risk of sounding stupid: is there an advantage to one over the other that I'm not seeing? I mean, I dislike the "private" notation; they're not private. I realize the prototype chain is shared between objects, but they're private. Short of altering x and y across all objects at runtime, or saving memory, I'm not sure of the reason.
I'm sure there's a good reason, but if someone cares to enlighten me further, that'd be awesome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您喜欢 Crockford 的作品,我建议您观看他的 JavaScript 系列,其中他描述了为什么他避免使用下划线并更喜欢驼峰符号。
http://www.yuiblog.com/crockford/
直接回答你的问题,没有任何表现使用下划线的优点,它只是一种编程风格偏好。
If you like Crockford's work, I'd suggest watching his JavaScript series where he describes why he avoids using underscores and prefers camelNotation.
http://www.yuiblog.com/crockford/
To answer your question directly, there is no performance advantage for using underscores, it is simply a programming style preference.
使用
_
表示法的三个原因:在这两个方向上还有其他争论,但它变得更加哲学化 - 关于是否信任程序员的代码或强制执行“良好实践”,但我不会去那里;)
Three reasons for using
_
notation:There are other arguments in either direction, but it gets more philosophical - about whether to trust programmers with your code or to enforce "good practice", but I won't go there ;)