0

I'm wondering what is better to Imagine in a library I have an object that stores some variables. Some of them do not fit semantically or contextually in that variable but they are used for some functions in that object. Would be better to store them inside that object as private variables if I want them not to be used except by those functions, or to declare them externally inside the IIFE that prepares the library and use those variables as closures?

Imagine:

let func = (function(){
  let func = function(){
     let a = "hello";
     this.sayHello = function(){
        alert(a);
     };
  }

  //Extend object etc and do some other things.
  return func;
})();

OR

let func = (function(){
  let a = "hello";

  let func = function(){
     this.sayHello = function(){
        alert(a);
     };
  }

  //Extend object and do some other things.
  return func;
})();
Lorthas
  • 376
  • 3
  • 11
  • Not sure those two examples are comparable... doesn't seem you need a closure – elclanrs May 31 '16 at 18:08
  • What kind of performance are we talking about? In theory, doing something n times is taking more time than doing the same thing only once. – Felix Kling May 31 '16 at 18:08
  • Creating that object one single time, or more, if it taking more time for the engine to get operate with that variable and if due to storing it in one place or another is taking more memory. I know it's a bit dumb example, but I thought it would be ok. – Lorthas May 31 '16 at 18:13
  • related: [Is a closure for dereferencing variables useful?](http://stackoverflow.com/q/8288664/1048572). In your case of "re-creating" a string (from that literal) hardly will matter as strings are interned anyway. – Bergi May 31 '16 at 21:03
  • @Redu Oh, sorry for not being as smart and aknowledged as you mr perfect. If you are going to help do it, otherwhise leave. So what if I want to create an object inside the IIFE and at the same time create private variables and functions but return only an object that is going the one that is going to be used? I felt the necessity of doing like that. If you know how I could do it better just tell me how, otherwhise shut up. I'm learning and I know I can make mistakes and that's why I'm here, cause I don't know everything, like a lot of people want to make others think about them. – Lorthas Jun 01 '16 at 18:51
  • @Redu So, something similar done here: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html I know mine it's not exactly the same. – Lorthas Jun 01 '16 at 19:07
  • @Lorthas OK man take it easy... cool... these are not regular JS and i am not trying to be start ass... when you got more and more involved in JS you will most probably feel like me. But OK it's a legit question which still drains my life energy. Please give me the chance to say so. – Redu Jun 01 '16 at 20:00

0 Answers0