Many plugins utilize an underscore to indicate a function is private while still allowing public access. But why? We have options like .call, .apply, or .bind for managing the "this" keyword, or we can use the "self" pattern which is reportedly 60% faster according to this discussion: Will Function.prototype.bind() always be slow?
Is it considered lazy programming or is there something I'm overlooking?
Example of exposing a private function:
var simplifiedPlugin = function() {
this.name = 'simples';
this._privateFunc = function() {
console.log('Why am I here?');
}
this.publicFunc = function() {
// stuff, then
this._privateFunc();
}
}
var pluginInstance = new simplifiedPlugin();
Utilizing the self pattern:
var selfSimplifiedPlugin = function() {
var self = this;
this.name = 'self is also simples';
function _privateFunc() {
console.log('Nobody knows am I here');
//I can use self instead of this
}
this.publicFunc = function() {
// stuff, then
_privateFunc();
}
}
var anotherInstance = new selfSimplifiedPlugin();
With the self pattern, the private function can still access the this context by using self.fn() instead of this.fn()