As a C# programmer, I have a bit of a habit of making things private that can and should be private, and I always get a weird feeling when a JS type exposes all its private parts to me (and that feeling is not 'aroused'). Say I have a type that has a draw
method, which internally calls drawBackground
and drawForeground
, which make no sense to be called on their own. How should I implement this?
Option 1
Foo = function(){
this.draw();
};
Foo.prototype.draw = function(){
this.drawBackground();
this.drawForeground();
};
Foo.prototype.drawBackground = function(){};
Foo.prototype.drawForeground = function(){};
Option 2
Foo = (function(){
var constructor = function(){
this.draw();
};
var drawBackground = function(){};
var drawForeground = function(){};
constructor.prototype.draw = function(){
drawBackground.call(this);
drawForeground.call(this);
};
return constructor;
})();
The difference, of course, being that in the first example, the drawBackground
and drawForeground
methods are part of the public API, while they are hidden to the outside in the second one. Is that desirable? Which one should I prefer? Am I wrong to apply my C# habits to Javascript and should I make everything extensible and override-able in Javascript? And what are the performance implications of the .call(this)
?