开发者

Privacy: Underscored prototype properties or encapsulated variables?

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 see开发者_运维问答ing? 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.


Three reasons for using _ notation:

  1. As you mentioned, performance. Functions are not recreated with each construction.
  2. Debugging. It's easy to view all the properties of an object at runtime.
  3. Structure. It's easy to break parts of the code into different files, or inherit properties in child "classes". Variables made private by closures restricts how you can organise your code. This is kind of like the argument to use protected/friend variables versus private variables in OOP languages.

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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜