Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class declared inside closure vs standard class without closure

Normally I use standard OOP approach based on prototype and my class looks like this

var std = function(){
   this.log = function(msg){ console.log("want to be private. " + msg) };
};

std.prototype = {
    logInfo: function(msg){
        this.log(msg);
    }
};

but in that case log is public method and anyone could use it. But I want to make it private, but still available in methods declared in prototype. For that we will need closures. Code will change to this

var closureStd = (function(){
var std = function(){};
var log = function(msg){ console.log("I'm really private, youhooo!" + msg) };

std.prototype = {
    logInfo: function(msg){
        log(msg);
    }
};

return std;
})();

So my question: what is the difference between std and closureStd and what is the price I need to pay to be able to call private methods from prototype?

like image 486
Ph0en1x Avatar asked Aug 14 '13 10:08

Ph0en1x


1 Answers

what is the difference between std and closureStd?

The std constructor creates a new method on every invocation while closureStd does not. You should've made it

function std(){}
std.prototype = {
    log: function(msg){ console.log("want to be private. " + msg) },
    logInfo: function(msg){ this.log(msg); }
};

And, of course (you already know) the log function in the closureStd is stored in a (private) variable while on the std instance it's accessible (and overwritable) from outside on each instance (or on their prototype). In the closure it's a variable lookup in the scope chain (which can assumed static), while for the method it's a property lookup on an object (and its prototype chain), which might be dynamic but is equally optimized in modern engines.

what is the price I need to pay to be able to call private methods from prototype?

None. The module pattern is common and cheap, variable lookups in a static chain are very fast. I'd rather worry about memory since you're creating so many method instances in the constructor approach.

like image 108
Bergi Avatar answered Oct 01 '22 02:10

Bergi