JavaScript,在不使用eval(Revearing模式)的情况下,将私有函数作为公共方法内的字符串调用

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

本文关键字:函数 调用 字符串 方法 情况下 eval JavaScript 模式 Revearing      更新时间:2023-09-26

我正试图在揭示模式中调用一个私有函数。这是我的代码:

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();
});

有人能帮我吗?

谢谢!

使您的私有函数成为对象的属性?

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

你的其他尝试都失败了,原因不同:

  • functionString.call('test')永远不会工作,因为functionString引用了字符串文字。它没有call方法。

  • window[module.privateMethod]('test')不起作用,因为首先,module没有属性privateMethod。如果是这样,那就不是"私人的"。这意味着您正在尝试调用window[undefined],它不是一个函数。