Computer >> Computer tutorials >  >> Programming >> Javascript

What is the drawback of creating true private methods in JavaScript?


Creating truely private methods in Javascript causes each object to have its own copy of the function. These copies are not garbage collected until the object itself is destroyed.

Example

var Student = function (name, marks) {
   this.name = name || ""; //Public attribute default value is null
   this.marks = marks || 300; //Public attribute default value is null
   // Private method
   var increaseMarks = function () {
      this.marks = this.marks + 10;
   };
   // Public method(added to this)
   this.dispalyIncreasedMarks = function() {
      increaseMarks();
      console.log(this.marks);
   };
};
// Create Student class object. creates a copy of privateMethod
var student1 = new Student("Ayush", 294);
// Create Student class object. creates a copy of privateMethod
var student2 = new Student("Anak", 411);