声明调用辅助函数的javascript原型函数的正确方法是什么

时间:2013-08-29 08:50:17

标签: javascript performance prototypal-inheritance

我正在尝试确定声明javascript“class”使用的辅助函数的最佳实践。例如:

方法#1:

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

function HeavilyInstantiated() {}

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

方法#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 个答案:

答案 0 :(得分:4)

我更喜欢方法3,将其声明为构造函数的属性:

function HeavilyInstantiated() {}

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

您仍然只有一个辅助方法实例,但它不会污染全局命名空间或HeavilyInstantiated的实例(它不在其原型链上)。