Display data stored in the Weakmap object

Asked

Viewed 25 times

2

var Pessoa = (function(){
    var dadosPrivados = new WeakMap();
    function Pessoa(nome, idade, sexo){
        dadosPrivados.set(this,{nome: nome});
        dadosPrivados.set(this,{idade: idade});
        dadosPrivados.set(this,{sexo: sexo});
    }
    Pessoa.prototype.getDados = function(){
        return dadosPrivados.get((this).nome, (this).idade, (this).sexo);

    };
    return Pessoa;
}());

var rafael = new Pessoa(
    {nome: 'Rafael'},
    {idade: '26'},
    {sexo: 'M'}
);

console.log(rafael.getDados());

When executing the code, only the name "Rafael" appears. The error is in my prototype or in the insertion of data in the object rafael?

1 answer

1

I believe you’re overwriting the data with followed dadosPrivados.set, that is, the value of the object will be the last dadosPrivados.set which relates to sex. And the object rafael should pass only one object with the data (and not 3 separate), since it is using only 1 object WeakMap(). Behold:

var Pessoa = (function(){
    var dadosPrivados = new WeakMap();
//    function Pessoa(nome, idade, sexo){
    function Pessoa(dados){
        dadosPrivados.set(this,dados);
//        dadosPrivados.set(this,idade);
//        dadosPrivados.set(this,sexo);
    }
    Pessoa.prototype.getDados = function(){
        return dadosPrivados.get(this);

    };
    return Pessoa;
}());

var rafael = new Pessoa (
    {nome: 'Rafael',
    idade: '26',
    sexo: 'M'}
);

console.log(rafael.getDados()); // retorna o objeto inteiro
console.log(rafael.getDados().nome); // retorna o nome

  • So just put all the data inside the same object, got it. I spent a lot of time trying to figure it out myself, thank you very much!

Browser other questions tagged

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