Private method in JAVASCRIPT class

Asked

Viewed 91 times

0

How to define a private method in a class JavaScript in order to make the method msg_privada as private (not externally visible) without changing the rating pattern?

The method msg_privada must be accessed only by the class object and not externally.

class TesteVisibilidade{

    // método público
    msg(input_msg){
      this.msg_privada(input_msg);
    }
    
    // método privado
    msg_privada(input_msg){
      alert('msg privada: ' + input_msg);
    }
}

let t = new TesteVisibilidade();
t.msg('Olá mundo!'); // emite alerta: "msg privada: Olá mundo!"
t.msg_privada('deveria dar erro!'); // Não deveria ser acessível (deveria resultar em ERRO)

  • See if this answer from another question helps you: https://answall.com/questions/328202/class-privada-em-javascript/328721#328721

1 answer

0

Without changing the notation pattern is not possible, you can use typescript that adds various concepts of typed languages (But your method will not be private really, only typescript will complain that you are trying to access a private parameter/method, but when you generate your javascript, you can access it normally), or use Ipife in js to create a scope for your function/class, example using the Ife:

(function(root){

	const camelCase = (nome) => nome.substring(0, 1).toUpperCase() + nome.substring(1, nome.length);

	class Pessoa {
		constructor (nome) {
			this.nome = nome;
		}

		get nomeCamelCase () {
			return camelCase(this.nome);
		}

	}

	root.Pessoa = Pessoa;

})(window);

//Não tenho acesso ao camelCase diretamente, somente ao Pessoa que adicionei no window
const nome = new Pessoa('jonathan').nomeCamelCase; // "Jonathan"
console.log(nome);
console.log(Pessoa);
console.log(camelCase);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.