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.
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.