Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 738
cbelizon Avatar asked Apr 21 '26 23:04

cbelizon


1 Answers

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.

like image 146
James Allardice Avatar answered Apr 23 '26 13:04

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!