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

大城市里の小女人 提交于 2019-12-07 15:44:30

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/17294443/javascript-call-private-function-as-a-string-inside-public-method-without-using

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