0

In order to reduce memory usage, I would like to assign several Javascript classes a prototype function.

My previous example was inadequate to explain the situation. A new, contrived example is shown below. In production scenarios, the function will likely have many more arguments, many more classes and instances will be using the prototype; some of which may be written by other developers.

function displayWeightedScore(metricOne, metricTwo, metricThree) {
    console.log((metricOne * 0.15) + (metricTwo * 1.25) + (metricThree * 0.5));
}

ScoringSystemOne.prototype.displayWeighedScore = displayWeightedScore;
CalculatorTwo.prototype.displayWeightedScore = displayWeightedscore;
ScoreCalculatorThree.prototype.displayWeightedScore = displayWeightedScore;
//etc..

Each class needs to pass in a different set of metrics or some of the same metrics in a different order. To me this means I would then write a closure or object method to capture the class-specific arguments and ordering and then call the prototype function.

However, I understand this will negate the memory savings of using prototype functions in the first place.

Is there a neat trick, some form of syntactic sugar, or best-practice technique to binding a set/ordering of arguments (arguments either unique per-class or per-class-instance) to a prototype function call without losing the memory savings of using prototypes?

5
  • Premature optimizations ... Commented Nov 29, 2019 at 22:31
  • 1
    micro optimisations Commented Nov 29, 2019 at 22:31
  • "this means I would then write a closure or object method to capture the class-specific arguments and ordering and then call the prototype function" - there's no reason why this object method couldn't be placed on the respective prototype object as well - having the same memory-saving advantage over creating closures inside the constructor function for each individual instance. Commented Nov 30, 2019 at 1:20
  • There's no good reason why your displayWeightedScore function should be a prototype method at all, it does not use the this keyword to refer to an instance object. You should keep it as a plain function declaration and simply call it. Commented Nov 30, 2019 at 1:21
  • Please show us the full code of your example, involving all the calls that you want to do with their correct results, how it would look like if you were not using prototypes. Only then we could advise where, what and whether to optimise. Commented Nov 30, 2019 at 1:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.