简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM