Private methods in Javascript classes

Question:

my question is how to define private methods in javascript classes so that they cannot be accessed directly.

class User {
  constructor(name, password, email) {
		this.name     = name;
		this.password = password;
		this.email    = email;
  }

  privado(){
  	console.log("Accediste a un metodo privado")
  }
}

var u = new User("usuario","123","usuario@example.com");
u.privado();

Try defining variables outside the constructor but it doesn't work.

Answer:

JavaScript does not implement object-oriented programming the same as languages ​​like Java, C #, etc. In JavaScript, there is basically no concept of encapsulation . Even so, due to its great flexibility you can simulate it with some ingenuity.


Referencing variables / functions

It is the simplest and most practical. You create the functions or variables outside the class and the references inside the class.

 class User { publico () { console.log('Soy un método público'); privado(); // se ejecuta correctamente } } let pepito = new User(); pepito.publico(); pepito.privado(); // pepito.privado is not a function function privado () { console.log('Soy un método privado'); }

Using Factories

Remember: there is no concept of classes in Javascript. Even in ES6 and the arrival of the class keyword still does not exist as such. JavaScript is a prototyped language. Even if you use the new syntax to create "classes" , you are creating functions with a prototype.

This form is the one that is used to use when you want to implement private variables or methods. The trick is to return an object that refers to the function's own and local variables and / or methods in the object to be returned. This is the magic of closures .

 function User () { const privado = function () { console.log('Soy un método privado'); } return { publico () { console.log('Soy un método público'); privado(); // se ejecuta correctamente } } } let pepito = User(); pepito.publico(); pepito.privado(); // pepito.privado is not a function
Scroll to Top