Search code examples
javascriptstringfunctiondesign-patternsprivate

JavaScript, call private function as a string inside public method without using eval (Revealing pattern)


I'm trying to call a private function inside the revealing pattern. This is my code:

var module = (function(){
    var privateMethod = function(val) {
        console.log(val);
    }
    var publicMethod = function() {
        var functionString = "privateMethod";
        /** This what I tried
        functionString.call('test');
        window[module.privateMethod]('test');
        */
    }
    return {
        init: publicMethod
    }
})();

$(document).ready(function(){
    module.init();
});

Someone could help me?

Thanks!


Solution

  • Make your private functions properties of an object?

    var module = (function(){
        var privateFuncs = {
            privateMethod: function(val) {
                console.log(val);
            }
        };
        var publicMethod = function() {
            var functionString = "privateMethod";
            privateFuncs[functionString]('test');
        };
        return {
            init: publicMethod
        };
    })();
    

    Your other attempts both fail, for different reasons:

    • functionString.call('test') will never work because functionString refers to a string literal. It doesn't have a call method.

    • window[module.privateMethod]('test') won't work because firstly, module doesn't have a property privateMethod. It wouldn't be "private" if it did. That means you're attempting to invoke window[undefined], which is not a function.