How to leave variables privately in Javascript?

Asked

Viewed 1,476 times

5

How to leave a private variable, because I had trouble using the same variable name that was already implemented in another JS file and that I didn’t remember.

How to create this private variable to use only in the file?

2 answers

9


In the file just use a var to declare the variable. Still not ideal. Variables must be more local yet. The ideal is to declare variables only within functions. You can also do this on objects. Only object variables usually have public visibility (even though the scope is private).

Creating variables with private visibility is possible with a trick. This is done in the object constructor with local variables to the constructor. Thus:

function Container(param) {
    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }
    this.service = function () {
        return dec() ? that.member : null;
    };
    this.member = param;
    var secret = 3;
    var that = this;
}
var obj = new Container('abc');
console.log(obj.service());
console.log(obj.service());
console.log(obj.service());
console.log(obj.service());
console.log(obj.secret); //isto dá erro

I put in the Github for future reference.

The technique with more details can be seen from Douglas Crockford’s famous article.

All three variables are local (the parameter is always local), and by definition only accessible within the constructor. The this.member is a public member of the object. JS is even more restricted than other languages. These object members can only be accessed by private method. Not even public methods of the object can access them directly.

Private methods are the functions declared within the constructor. This is the case for dec(). To make the communication between private and public methods we create a method within the builder but through the this, so it is both private (to the builder) and public (accessible by the reference of the object), so it is a privileged method. This is the method service(). He may call dec() and access that which are private, and is accessible outside the object.

The mechanism that allows this can be better understood in the question about closures.

3

Marcio, first you need to understand a little about the scope of the variables.

So let’s start with the global scope:

//se declarado fora de qual quer função/objeto.
var variavel = "Hello World!";
//se declarado em qual quer ponto do codigo.
window["variavel"] = "Hello World!";
window.variavel = "Hello World!";

the three statements above point to the same variable, in the case of the global variable variavel.

if you want your variable to be in the whole code, but cannot be edited, you can make use of the Object.defineProperty:

Object.defineProperty(window, "variavel", {
  value: "Hello Wolrd!"
});

console.log(variavel); // "Hello Wolrd!"
variavel = "Tentativa de Editar";
console.log(variavel); // "Hello Wolrd!", a atribuição acima não surtiu efeito.

However, I believe that in your case, the best is to define a scope, for this there are some techniques, such as a IIFE

(function () {
  var variavel = "Hello World";
  console.log("dentro do IIFE -> " + variavel); //"Hello World"
  window.setTimeout(function () {    
    console.log("dentro do IIFE -> " + variavel); //"Hello World"
    console.log("global dentro do IIFE -> " + window.variavel); //"Tentativa de Editar"
  }, 2000);
})();

variavel = "Tentativa de Editar";
console.log("fora do IIFE -> " + variavel); //"Tentativa de Editar"
window.setTimeout(function () {    
  console.log("fora do IIFE -> " + variavel); //"Tentativa de Editar"
}, 2000);

Note that inside the IIFE to variavel continues with the value Hello World, although in the global scope it has received the value Tentativa de Editar

Browser other questions tagged

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