JavaScript,将public函数调用为public方法中的字符串,而不使用eval(显示模式) [英] JavaScript, call private function as a string inside public method without using eval (Revealing pattern)

查看:108
本文介绍了JavaScript,将public函数调用为public方法中的字符串,而不使用eval(显示模式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在透露模式中调用私有函数。这是我的代码:

  var module =(function(){
var privateMethod = function(val){
console.log(val);
}
var publicMethod = function(){
var functionString =privateMethod;
/ **这是我试过的
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 是一个字符串文字。它没有调用方法。


  • window [module。 privateMethod]('test')将不起作用,因为首先,模块没有属性 privateMethod 。它不会是私人的。这意味着你试图调用窗口[undefined] ,这不是一个功能。



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.

这篇关于JavaScript,将public函数调用为public方法中的字符串,而不使用eval(显示模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆