问题
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