Computer >> Máy Tính >  >> Lập trình >> Javascript

Hạn chế của việc tạo các phương thức riêng tư thực sự trong JavaScript là gì?

Việc tạo các phương thức riêng tư thực sự trong Javascript khiến mỗi đối tượng có bản sao hàm của riêng nó. Các bản sao này không phải là rác được thu thập cho đến khi bản thân đối tượng bị phá hủy.

Ví dụ

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);