Expose private variables in Revealing Module Pattern

让人想犯罪 __ 提交于 2019-12-02 23:38:47
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.

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/

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!