0

I'm trying to determine what is the best practice for declaring helper functions used by a javascript "class". For example:

Method #1:

// closure issues?
function helper(param) {
  return compute(param);   
}

function HeavilyInstantiated() {}

HeavilyInstantiated.prototype.computeHard = function(params) {
   var someResult = helper(params.prop1);
   return someResult;
}

Method #2:

function HeavilyInstantiated() {}

// still, only one instance for all objects instantiated?
HeavilyInstantiated.prototype.helper = function(param) {
   return compute(param);  
}
HeavilyInstantiated.prototype.computeHard = function(params) {
   var someResult = this.helper(params.prop1);
   return someResult;
}
alpinescrambler
  • 1,934
  • 16
  • 26
  • What do you mean by "closure issue"? – Bergi Aug 29 '13 at 09:37
  • possible duplicate of [How to implement Revealing prototype pattern?](http://stackoverflow.com/questions/9248655/how-to-implement-inheritance-in-js-revealing-prototype-pattern) – Bergi Aug 29 '13 at 09:39
  • What I meant by saying "closure issue" is that the helper function might be closured by every instance of HeavilyInstantiated. By maybe that's not the case- just gets pushed and popped off the stack??? Probably just "polluting" the global namespace. – alpinescrambler Aug 29 '13 at 16:53
  • No it's not in a closure - it is not in the function body of the `HeavilyInstantiated` constructor but outside. It's in the global scope indeed, and to avoid that pollution use the *revealing module* pattern. – Bergi Aug 29 '13 at 19:34

1 Answers1

4

I prefer method 3, declaring it as a property of the constructor:

function HeavilyInstantiated() {}

HeavilyInstantiated.helper = function(param) {
   return compute(param);  
}
HeavilyInstantiated.prototype.computeHard = function(params) {
   var someResult = HeavilyInstantiated.helper(params.prop1);
   return someResult;
}

You still have only one instance of the helper method, but it doesn't pollute the global namespace or the instances of HeavilyInstantiated (it is not on their prototype chain).

Tibos
  • 27,507
  • 4
  • 50
  • 64
  • Right, this is my objective, only one instance of helper, not polluting the global namespace or current scope, and looks like you've got a bonus - not polluting the prototype chain as well. I'll dig into this. thanks. – alpinescrambler Aug 29 '13 at 16:56