What is the way of declaring a proper prototype-like variable as in functions but using class notation in Javascript?
Some background:
Currently we have two ways of declaring a “class” templates with ES6
- using function
function Something(v) {
this.v = v;
}
Something.prototype.isSomething = true;
And then use it:
let sth = new Something(2);
As a result value contains instance variable sth.v = 2;
and prototype variable (shared among all instances) as sth.prototype.isSomething = true
The isSomething variable will become an instance variable when we change it, for a particular instance, like so:
sth.isValue = false. Then we have sth.v = 2 and sth.isSomething = false, and isSomething will ‘move’ from .prototype to instance in the structure of the object (it is possible to verify in the console). Such case is increasing memory only for the edited instance as for the rest of Something instances the isSomething property will still be pointing to the .prototype.
- using class
class Something {
isSomething = true; // is this the correct usage?
constructor(v) {
this.v = v;
}
}
And then use it:
let sth = new Something(2);
In this case
the sth.v = 2 as in previous example but sth.prototype.isSomething is not existing in chain (at least this is how it is shown in the browser console).
Instead, the isSomething variable is by default stored as an instance variable by default. This is not intended because, as per my understanding, each instance will now duplicate isSomething property, increasing the memory usage.
Does the class notation triggers some optimisation in JS engine under the hood to handle aforementioned drawbacks?
I am aware of availability of static Value.isValue option but this is not the same as class variables have different usage.
The consideration here is that very often the code is ‘refactored’ from javascript functions or IIFE’s to new ES6 classes but I wonder if brings described memory penalties. As far as I remember for high performance the .prototype props were used as much as possible in the past and made the difference (example being many graphics libs like Three.js).