Javascript动态函数调用名称 [英] Javascript Dynamic Function Call with Name

查看:59
本文介绍了Javascript动态函数调用名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下伪Javascript代码:

So I have the following pseudo Javascript code:

var Class = (function(window, document, $) {
    function meth_1()
    {
        //some code
    }

    function meth_2()
    {
        //some code
    }

    function meth_3()
    {
        //some code
    }

    function meth_4()
    {
        //some code to call other three functions dynamically
    }

    Class = {
        meth_1: meth_1,
        meth_2: meth_2,
        meth_3: meth_3,
        meth_4: meth_4
    };
    return Class;

})(window, document, jQuery);

meth_4 函数中,我想要通过将函数名称作为字符串传递来动态调用其他3个函数。我该怎么做?!

In the meth_4 function, I want to call the other 3 functions dynamically by passing the function name as a string. How can I do this?!

在这个相关的StackOverflow问题,答案提供了如何在窗口范围内完成此解决方案的解决方案,即 window [function_name]()。但是,我想知道如何在我的特定情况下做到这一点。

In this related StackOverflow question, the answer provides a solution to how this could be done in window scope i.e. window[function_name](). However, I'd like to know how I can do it in my particular circumstance.

谢谢。

编辑

我选择的答案可行。您还可以执行以下操作:

The answer I selected works ok. You could also do the following:

var Class = (function(window, document, $) {
    var meth_func = {
        meth_1: function(){/**your code**/},
        meth_2: function(){/**your code**/},
        meth_3: function(){/**your code**/}            
    }

    function meth_4(func_name)
    {
        meth_func[func_name]();
    }

    Class = {
        meth_4: meth_4
    };
    return Class;

})(window, document, jQuery);

如果您希望将这三个函数动态调用私有,这可能会更好。

This would probably work better if you wanted to make private those three functions being called dynamically.

推荐答案

由于你想在对象范围而不是窗口范围内使用括号表示法调用函数,你可以使用 this 而不是窗口

Since you want to call functions using bracket notation in object scope, not window scope, you can use this instead of window:

function meth_4()
{
    this["meth_1"]();
    this["meth_2"]();
    this["meth_3"]();
}

这篇关于Javascript动态函数调用名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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