How to leave variables privately in JavaScript?

5

asked by anonymous 28.05.2016 / 00:23

2 answers

9

In the file just use var to declare the variable. Still not ideal. Variables should be more local still. The ideal is to declare variables only within functions. You can also do this on objects. However, object variables often have public visibility (even if the scope is private).

If you want to create variables with private visibility it is possible with a trick. This is done in the constructor of the object with local variables to the constructor. So:

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');
document.body.innerHTML += obj.service() + '<br>';
document.body.innerHTML += obj.service() + '<br>';
document.body.innerHTML += obj.service() + '<br>';
document.body.innerHTML += obj.service() + '<br>';
document.body.innerHTML += obj.secret; //isto dá erro

The technique in more detail 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. 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 object methods can access them directly.

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

The mechanism that allows this can best be understood in closures question.

    
28.05.2016 / 00:53
3

Marcio, you first need to understand a bit 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 this case the global variable variavel .

If you want your variable to be all code, but can not be edited, you can use 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 think in your case, it is best 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 within IIFE to variavel continues with the value Hello World , although in the global scope it has received the value Tentativa de Editar

    
28.05.2016 / 00:54