JavaScript does not implement object-oriented programming the same as languages such as 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's the simplest and most practical thing. You create the functions or variables outside the class and the references within 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: in Javascript the classes concept does not exist . Even in ES6 and the arrival of the reserved word class
still does not exist as such. JavaScript is a prototyping language. Even if you use the new syntax to create "classes" , you will be creating functions with a prototype.
This form is the one that is customary to use when you want to implement variables or private methods. The trick is to return an object that references to variables and / or own methods and local of the function 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