Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object's - private methods: which way is better

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

like image 643
Praveen Prasad Avatar asked Dec 02 '22 03:12

Praveen Prasad


1 Answers

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;
};
like image 147
jAndy Avatar answered Dec 24 '22 13:12

jAndy