带有名称的 Javascript 动态函数调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15202942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:51:30  来源:igfitidea点击:

Javascript Dynamic Function Call with Name

javascriptjquery

提问by Obinwanne Hill

So I have the following pseudo Javascript code:

所以我有以下伪Javascript代码:

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

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

meth_4函数中,我想通过将函数名称作为字符串传递来动态调用其他 3 个函数。我怎样才能做到这一点?!

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.

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

Thanks.

谢谢。

EDIT

编辑

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.

如果您想将动态调用的这三个函数设为私有,这可能会更好。

采纳答案by Frédéric Hamidi

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

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

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

回答by strandel

I don't know why you would want that (also 'Class' is not good as a variable name), but could be done like this:

我不知道你为什么想要那个(“类”也不适合作为变量名),但可以这样做:

var Class = (function (window /*, ... */) {
  return {
    func1: function () {console.log('1')}
  , func2: function () {console.log('2')}
  , func3: function () {console.log('3')}
  , func4: function (funcName) {
      console.log('4+')
      this[funcName]()
    }
  }
})(window)

Class.func4('func3')

回答by Rune FS

Here's an implementation that can do what you want. If you pass a string it will simply look up the appropriate function and execute it. However since functions in JS are indeeed objects them self you can pass those around and to show that I've extended the functionality a bit compared to what you ask for. If you pass a function (actual anything but a string) it will (try to) invoke it

这是一个可以执行您想要的操作的实现。如果您传递一个字符串,它只会查找适当的函数并执行它。但是,由于 JS 中的函数确实是它们自己的对象,因此您可以传递它们并表明与您要求的功能相比,我已经扩展了一些功能。如果您传递一个函数(实际上是字符串以外的任何东西),它将(尝试)调用它

meth_4 = function(fun){
   if(typeof fun === 'string'){
       this[fun](args.slice(1));
   } else { //assuming it's a function
       if(arguments.length == 1)
          fun.call(this,[])
       } else {
          fun.apply(this,arguments.slice(1))  
       }
   }
}

JavaScript objects are, or at can be treated as, a key/value pair collection. Any function or property can be access in two semantically equivalent ways

JavaScript 对象是或可以被视为键/值对集合。可以通过两种语义等效的方式访问任何函数或属性

obj.keyor obj["key"]in certain cases only the latter can be used. E.g. if the property is called property nameyou can't do obj.property namebut can do obj["property name"]

obj.key或者obj["key"]在某些情况下只能使用后者。例如,如果该属性被调用,property name你不能做obj.property name但可以做obj["property name"]