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","[email protected]");
u.privado();
I tried defining variables outside the constructor but it doesn't work.
JavaScript does not implement object-oriented programming in the same way 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.
Using Factories
This form is the one that is usually used when you want to implement private variables or methods. The trick is to return an object that references variables and/or local methods of the function in the object to be returned. This is the magic of the
closures
.Try this,
Although I liked @jolsalazar's answer and it seemed quite practical, I want to leave the way I solved this and that seems a bit more 'elegant' to me:
Let me explain my code a bit:
We create an ' object ' with a self invoking function and use the method
prototype
to 'inject' a new function and make it 'public' by passing the context as an argument to the call function.this
It should be noted that
javascript
there are no reserved words such aspublic
orprivate
to define methods within oneClass
and for this reason a type of 'hack' must be carried out as shown above.Although JavaScript is not an Object Oriented language, we can get closer considering the definition of a private method.
The first thing to do is omit the this keyword from the constructor.
We define the private(); and a public method called method(); which invokes the private methods and this will be the one that we can call from external javascript methods.
In this way, remember that variables and methods with this are public and with var they are private.
Something that works very well is to implement class members with # in front