I use the following pattern all of the time:
;(function(ns){
var _str = 'hello';
ns.hello = function(){
console.log(str)
}
})(this.app = this.app || {});
app.hello(); // logs 'hello' to the console
I'm trying to to do more OO type things and want to reuse this pattern. What I've come up with is the following that looks very similar to the above.
var App = (function(){
var _str= 'hello';
function App(){}
App.prototype.hello = function(){
console.log(_str);
}
return App;
})();
var instance = new App();
instance.hello(); // logs 'hello' to the console
This next variation makes use of the "that" idea but i dont see the utility of it in this use case:
var App = (function(){
var that = this;
this._str= 'hello';
function App(){}
App.prototype.hello = function(){
console.log(that._str);
}
return App;
})();
var instance = new App();
instance.hello(); // logs 'hello' to the console
Is it a worthwhile to wrap things in a closure when attempting to write in an OO fashion? Any drawbacks to the above constructors? Should i focus on learning a different pattern?