(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 private 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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With