Private Property / Protected JS / jQuery

Asked

Viewed 479 times

6

Is it possible to make an object in js/jQuery where it is visible only using the method, for example get / set? An example of an object:

if I give a console.log(pessoa.documeto), it will display the values, but what I wanted is to see if there is a way to make it 'private' or 'protected' equal to PHP and others.

var pessoa = {
        nome    : '' , //Publico
        idade   : '' ,  //Publico
        documentos : [
                //Protegido / Privado
                {
                    CPF : {
                num         : '' , 
                dataemissao : '' ,
                ufemissao   : '' ,
                obrigatorio : true ,
                status      : ''
            } ,
            RG : {
                num : '' ,
                dataemissao : '' ,
                ufemissao   : '' ,
                obrigatorio : '' ,
                status      : false
            }
                }
        ] ,
        parentes : [
                {
            pai : {
                nome    : ''    ,
                idade   : ''    ,
                cpf     : ''    ,
            } ,
            mae : {
                nome    : ''    ,
                idade   : ''    ,
                cpf     : ''    ,
            },
            irmaos : [
                {
                    nome : ''   ,
                    idade : ''  ,
                    cpf : ''
                }
            ]
               }
        ] ,
        //Metodos
        get : function(propriedade){
            /*
            * Pega a propridade e tal,
            * mas nao vou descrever isso aqui agora =D
            */
        } ,
        set : function(proriedade , valor){
            /*
            * Seta a propriedade e bla, bla, bla...
            */
        }
     };
  • 1

    With literal object does not give, but it is possible to achieve something similar with the module Pattern.

  • Hmm, so I’ll have to take a look at some framework for JS/jQuery or create a function that would be class (PHP) and other functions inside that would be something like the methods. that ?

1 answer

7


The simplest way is to use a function to generate the object. All values that should be private would be visible variables only in the scope of this function. The getter and the Setter would be other functions in the same scope, and with access to these variables via closure (would basically be the same technique used in module Pattern, that I explained in another answer).

A simple example:

function criaObj() {
    var privado = "bla";

    function getPrivado() {
        return privado;
    }

    function setPrivado(val) {
        privado = val;
    }

    return {
        get: getPrivado,
        set: setPrivado
    };
}

// Uso
var obj = criaObj();
console.log(obj.getPrivado()) // "bla"
obj.setPrivado("foo");
console.log(obj.getPrivado()) // "foo"

Another option is to use a constructor function and Object.defineProperty (or Object.defineProperties) to create getters and setters "for real".

function Construtor() {
    var privado = "bla";

    // Cria propriedade bla (getter/setter) no objeto sendo instanciado
    Object.defineProperty(this, 'bla', {
        get: function() { return privado; },
        set: function(val) { privado = val; }
    });
}

var obj = new Construtor();
console.log(obj.bla); // "bla"
obj.bla = "foo";
console.log(obj.bla); // "foo"
  • I understood and thank you for your attention! I just did not give a positive because I missed 1 point to release =/

  • Quiet. Still I will complement the answer with another option a little more complex.

  • @Douglasdreer point granted, the question became legal

  • 1

    @Douglasdreer I don’t know if you ever saw the response update with another option.

  • I will test this update and then give you an opinion. Because the previous one I could not make work right.

  • It worked with you explained it to me and everything, but how would you do if there were several parameters ? function pessoa(){ var nome = '<insira seu nome>'; var idade = '<insira a idade>';&#xA;var array = ['branco' ,'loiro' , 'olhos claro'];&#xA;var object = {item : valor };&#xA;(...)&#xA;});&#xA;

Show 1 more comment

Browser other questions tagged

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