声明调用辅助函数的 javascript 原型函数的正确方法是什么 [英] What is the proper way to declare javascript prototype functions calling helper functions

查看:65
本文介绍了声明调用辅助函数的 javascript 原型函数的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

方法一:

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

推荐答案

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

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

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

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

这篇关于声明调用辅助函数的 javascript 原型函数的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆