Private methods in Javascript classes

7

My question is how to define private methods in javascript classes so that they can not 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 does not work.

    
asked by Edwin V 08.02.2017 в 17:38
source

4 answers

3

Try this,

class User {
  constructor(name, password, email) {
		this.name     = name;
		this.password = password;
		this.email    = email;
        var privado_ = function(){
          console.log('realmente esto es privado');
        };
    
       this.privado = function(){
  	      console.log("Accediste a un metodo privado");
          privado_();
       }
  }

}

var u = new User("usuario","123","usuario@example.com");
u.privado();
    
answered by 08.02.2017 / 18:00
source
5

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
    
answered by 08.02.2017 в 18:12
4

Although I liked the response of @jolsalazar and it seemed quite practical, I want to leave the way I solved this and that seems to me a bit more 'elegant':

var Salute = (function (){

    // Esta función es nuestro constructor
    function Salute(lang){
        this._lang = lang;
    }

    // Este es nuestro método privado
    function Hi(){
        if(this._lang == "en"){
            alert('Hi, I am a private method');
        }else if(this._lang == "es"){
            alert('Hola, Yo soy un método privado');
        }
    }

    // Este es nuestro método público
    Salute.prototype.sayHi = function () {
        return Hi.call(this);
    }

    return Salute;

})();

var salute_es = new Salute('es');

salute_es.Hi(); 
// La consola nos mostrará que Hi(); 
// no es una función válida

salute_es.sayHi();  
// Nos saldrá un alert con el texto 
// 'Hola, Yo soy un método privado'

I explain my code a bit:

We create an ' object ' with a auto-invoked function (in English self invoking function ) and use the prototype method for ' inject 'a new function and make it' public 'using the function call passing the context this as an argument.

It should be noted that in javascript there are no reserved words such as public or private to define methods within a Class and therefore a type of 'hack' must be performed as the previous one shown.

    
answered by 08.02.2017 в 18:09
4

Although JavaScript is not an Object Oriented language, we can approach it taking into account the definition of a private method.

  

Private methods are those methods that can be called from class methods, but never external to the class.

The first thing to do is omit the reserved word this in the constructor.

We define the private method (); and a public method called method (); which invokes private methods and this will be what we can call from external javascript methods.

In this way remember that the variables and methods with this are public and with private var.

class User {
 
 constructor(name, password, email) {
		var name     = name;
		var password = password;
		var email    = email;
        var privado  = function() { 
          console.log("Accediste a un metodo privado"); 
        }
        
        this.getPrivado = function(){ privado(); }
  }
  
}

var u = new User("usuario","123","usuario@example.com");
u.getPrivado();
    
answered by 08.02.2017 в 18:43