Question

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;
}
Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top