diff --git a/README.md b/README.md index 0a2e708..0952fe5 100644 --- a/README.md +++ b/README.md @@ -554,5 +554,37 @@ prototypes are much more flexible in the sense that they may be mutable or immutable. The object may inherit from multiple prototypes, and only contains objects. ``` - + + +- **[6.7](#javascript--private-methods) What is the drawback of creating true private methods in JavaScript?** +```javascript +One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance. + +var Employee = function (name, company, salary) { + this.name = name || ""; //Public attribute default value is null + this.company = company || ""; //Public attribute default value is null + this.salary = salary || 5000; //Public attribute default value is null + + // Private method + var increaseSalary = function () { + this.salary = this.salary + 1000; + }; + + // Public method + this.dispalyIncreasedSalary = function() { + increaseSlary(); + console.log(this.salary); + }; +}; + +// Create Employee class object +var emp1 = new Employee("John","Pluto",3000); +// Create Employee class object +var emp2 = new Employee("Merry","Pluto",2000); +// Create Employee class object +var emp3 = new Employee("Ren","Pluto",2500); +Here each instance variable emp1, emp2, emp3 has its own copy of the increaseSalary private method. + +So, as a recommendation, don’t use private methods unless it’s necessary. +``` **[⬆ back to top](#table-of-contents)**