Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose private variables in Revealing Module Pattern

I'm trying to implement the Revealing Module Pattern but I'm unable to expose a modified private property.

var myRevealingModule = (function(){

    var name = 'Diogo';

    function setName () {
       name = name + ' Cardoso';
    }

    return {
        fullName: name,
        set: setName
    };

}());

// Sample usage:
myRevealingModule.set();
console.log(myRevealingModule.fullName); // "Diogo" instead of the excepted "Diogo Cardoso".
like image 554
Diogo Cardoso Avatar asked Mar 12 '12 17:03

Diogo Cardoso


2 Answers

return {
    fullName: name,
    set: setName
};

That uses the values of name and setName. It does not create a reference to the variable. Effectively, name is copied.

You need to create a corresponding getName method, to take advantage of closures so that you can keep a reference to a variable.

like image 52
lonesomeday Avatar answered Oct 01 '22 22:10

lonesomeday


var myRevealingModule = (function(){

    var name = 'Diogo';

    function setName () {
       name = name + ' Cardoso';
    };

    function getName () {
       return name;
    };

    return {
        fullName: name,
        set: setName,
        get: getName
    };

}());

http://jsfiddle.net/yeXMx/

like image 25
Alex Avatar answered Oct 01 '22 21:10

Alex