0

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

方法#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;
}
4

1 回答 1

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 的实例(它不在它们的原型链上)。

于 2013-08-29T09:03:07.820 回答