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?

AMemberofDollars
  • 331
  • 2
  • 14
  • Premature optimizations ... – Jonas Wilms Nov 29 '19 at 22:31
  • 1
    [micro optimisations](https://stackoverflow.com/a/3471000/860099) – Kamil Kiełczewski Nov 29 '19 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*. – Bergi Nov 30 '19 at 01: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. – Bergi Nov 30 '19 at 01: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. – Bergi Nov 30 '19 at 01:23

0 Answers0