1

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?

user1990962
  • 361
  • 1
  • 11
  • A great explanation is here https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Niladri Jan 05 '18 at 18:45
  • What you're showing there is similar to the "Module Pattern". There are reasons to use it and reasons not to use it. Take a look here: [Learning JavaScript Design Patterns](https://addyosmani.com/resources/essentialjsdesignpatterns/book/) – gforce301 Jan 05 '18 at 18:47

0 Answers0