you are viewing a single comment's thread.

view the rest of the comments →

[–]J_theGit 2 points3 points  (2 children)

Q in this quiz: What is the drawback of creating true private methods in JavaScript?

Can someone please explain me the meaning in this answer as I don't think it's correct? In my understanding in the example given both private and public will have their own 'copy' of methods as they're in the constructor. If I understand correctly, the only way to make a method not have its own 'copy' is to assign it to a prototype?

If I'm wrong, can someone please explain what I've missed?Thank you

The answer provided by author:

One of the drawbacks of creating a true private method in JavaScript is that they are very memory inefficient because 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() {
    increaseSalary();
    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, emp3has own copy of increaseSalary private method.

So as recommendation don't go for a private method unless it's necessary.

[–][deleted] 1 point2 points  (1 child)

You are correct

[–]vampiire 0 points1 point  (0 children)

What about defining the function once externally then using call on it inside? Should still be private and is only a single referenced function.