JavaScript class memory usage

So, I am making some similar JavaScript classes like

MyClass = function()
{
   var x;

   this.sayX = function()
   {
      alert(x);
   }
}

but i also saw

MyClass = function()
{
   this.x = 0;
}

MyClass.prototype.sayX = function()
{
   alert(this.x);
}

The big question is: am I still losing memory space in modern JavaScript machines, or are they able to see duplication in my method and optimize them? The reason I ask is because I prefer to hide data and should not prefix absolutely everything with 'this'.

+3
source share
2 answers

. prototype , . , , .

, , , .

MyClass = function () {
   var x;
   // public method with access 
   // to private variables
   this.sayX = function () {
      alert(x);
   };
}
// method that doesn't need access to private variables
MyClass.prototype.sharedMethod = function () {
   // ...
}

, . ,

// everything will be created for every
// instance, but the whole thing is nicely
// wrapped into one 'factory' function
myClass = function () {
   // private variables
   var x;

   // private methods
   function doSomethingWithX() {}

   // public interface
   return {
     sayX: function () {
       alert(x);
     },
     publicMethod: function () { .. },
     // ...
   };
};

, myClass , new !


- , :

MyClass = function (x, y, whatever) {
   this._init.apply(this, arguments);
}

// The prototype creates a scope for data hiding.
// It also includes a constructor function.
MyClass.prototype = (function () {
   var x; // private
   return {
     _init: function (x_in) {
       x = x_in;
     },
     sayX: function () {
       alert(x);
     },
     // ...
   };
})();
+4

Source: https://habr.com/ru/post/1773469/


All Articles