Expose private variables in Revealing Module Pattern
Asked Answered
P

3

12

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".
Poesy answered 12/3, 2012 at 17:43 Comment(0)
M
24
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.

Monocyclic answered 12/3, 2012 at 17:47 Comment(0)
F
16
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/

Flowerer answered 12/3, 2012 at 17:45 Comment(0)
H
0

If your value is an attribute in an object or array, you can export the object or array and the export will be by reference so outside users will see updated changes. It's a little risky since the generic pattern of exporting variables has the scalar/object copy/reference dichotomy.

Hansom answered 15/11, 2015 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.