(function () {
function User() {
//some properties
}
//private fn 1
User.prototype._aPrivateFn = function () {
//private function defined just like a public function,
//for convetion underscore character is added
}
//private function type 2
//a closure
function _anotherPrivateFunction() {
// do something
}
//public function
User.prototype.APublicFunction = function () {
//call private fn1
this._aPrivateFn();
//call private fn2
_anotherPrivateFunction();
}
window.UserX = User;
})();
//which of the two ways of defining p开发者_运维技巧rivate methods of a javascript object is better way, specially in sense of memory management and performance.
Your "private function #1" is not private at all. Whereas version #2 is closured and therefore really is only accesible through your User
object.
There often is no "better", but in this case in that context, a closured function is perfectly hidden from the outside world (which is obviously better).
There still are rumours that closures create memory leaks, which is just wrong. Closures don't create memory leaks but the programmer does/can. Your example here is totally fine.
To have private methods, you should use almost the exact pattern.
var myObject = function() {
// privates
var a = 5,
b = 10,
c = a,
public = {};
public.getA = function() {
return a;
};
public.setA = function(v) {
a = v;
};
function privateOne() {
}
return public;
};
Creating closures is better if you absolutely must (or want to) hide the functions from the outside world.
Adding methods to the prototype is better if you care about:
- Memory, because then all instances will share the same (single) function rather than create one each.
- Testability, because you can't test a function that is hidden inside of a closure.
John Resig of jQuery has an excellent presentation of how to create scoop/prototyping/inherits etc.
http://ejohn.org/apps/learn/
精彩评论