简体   繁体   English

将函数及其参数存储在数组中以供稍后调用

[英]Storing functions and their parameters in an array to call later

I would like to store multiple functions and their parameters in an array that I will later loop over and execute.我想将多个函数及其参数存储在一个数组中,稍后我将循环执行该数组。 When putting the parens around the parameters, the function executes immediately and its array value becomes undefined.将括号放在参数周围时,函数会立即执行并且其数组值变为未定义。 I would like to prevent this from happening and call the function (with its parameter(s)) at a later time.我想防止这种情况发生并在以后调用该函数(及其参数)。 Here is an example of what I am trying to accomplish...这是我试图完成的一个例子......

function getTableAssignments(callbacks) {
    $.ajax({
        method: "POST",
        datatype: "jsonp",
        url: base_url + "users/getTableAssignments/" + event_id
    }).done(function (data) {
        tables = data;
        if (callbacks.length > 0) {
            $.each(callbacks, function (i, v) {
                v();
            });
        }
    });
}
getTableAssignments([func1(param1, param2), func2, func3(param3)]);

Storing the parameters is the problem.存储参数是问题。 Here is how to store the function references:以下是存储函数引用的方法:

getTableAssignments([func1, func2, func3]);

Here is how to bind the parameters to the functions prior to execution.下面是如何在执行之前将参数绑定到函数。 This returns a new function.这将返回一个新函数。 There are other ways to do it, but I think this would be the simplest.还有其他方法可以做到这一点,但我认为这将是最简单的。

var boundFunc1 = func1.bind(null, param1, param2);
var boundFunc3 = func3.bind(null, param3);

getTableAssignments([boundFunc2, func2, boundFunc3]);

You can also store your parameters in an object as arrays, and lookup those stored parameters with the function name, but that seems messy, so I won't expound on that method (and it would require you to change the calling to code the lookup the parameters).您还可以将参数作为数组存储在对象中,并使用函数名称查找这些存储的参数,但这看起来很混乱,因此我不会详细说明该方法(并且它需要您更改调用以对查找进行编码参数)。

If you haven't read up on bind, I'd recommend this video如果你还没有阅读绑定,我会推荐这个视频

You need to use function expressions:您需要使用函数表达式:

getTableAssignments([
    function() {func1(param1, param2); },
    func2,
    function() {func3(param3); }
]);

I think arrow functions would be a slick way of doing this:我认为箭头函数是一种巧妙的方法:

 function func1 (param) { console.log("func1 : " + param); } function func2 () { console.log("func2"); } function func3 (param1, param2) { console.log("func3 : " + param1 + ", " + param2); } function executeFunctions(funcs) { for (var i = 0, len = funcs.length; i < len; i++) { funcs[i](); } } favorateParam = "bob"; executeFunctions([ ()=>func1("dad"), ()=>func2(), ()=>func3("jane",favorateParam) ]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM