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