What is the proper way to declare javascript prototype functions calling helper functions

拈花ヽ惹草 提交于 2019-12-23 05:49:07

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/18506263/what-is-the-proper-way-to-declare-javascript-prototype-functions-calling-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!