使用定义时定义的参数创建一组匿名函数 [英] Create a set of anonymous functions with parameters defined at definiton time

查看:14
本文介绍了使用定义时定义的参数创建一组匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试逐步重构现有代码.我有一组已定义的函数,仅在一个内部参数上有所不同:

I'm attempting to gradually refactor existing code. I have a set of functions that are defined, and only differ by one of the internal arguments:

function loadGame1():void
{
    loadGame("save1");
}
function loadGame2():void
{
    loadGame("save2");
}
function loadGame3():void
{
    loadGame("save3");
}
//... snip many, many lines

// Note- I cannot pass function arguments at this time!
picker(loadGame1, loadGame2, loadGame3 ...);    

我正在尝试至少重构部分(我还不能完全替换整个内容,相互依赖太多).

I'm trying to refactor at least part of this (I can't completely replace the whole thing yet, too many interdependencies).

基本上,我希望能够生成一大组函数,这些函数之间的差异是一个内部参数:

Basically, I want to be able to generate a big set of functions with the difference between the functions being a internal parameter:

var fNames:Array = new Array("save1", "save2", "save3");
var funcs:Array = new Array();
for (var i = 0; i < fNames.length; i += 1)
{
    trace("Creating function with indice = ", i);
    funcs.push(
        function() : void 
        {
            saveGame(fNames[i]);
        }
    )
}

picker(funcs[0], funcs[1], funcs[2] ...);

然而,据我所知,闭包导致 i 的状态被维持在 for 循环的范围之外,并且任何调用任何生成函数的尝试都失败了-of-bounds 错误,这是您所期望的,因为 i 将在 i i 之前到达 fNames.size + 1fNames.size 计算结果为 false.

However, as I understand it, closure is causing the state of i to be maintained beyond the scope of the for loop, and any attempt to call any of the generated functions is failing with an out-of-bounds error, which is what you would expect given that i will reach fNames.size + 1 before i < fNames.size evaluates to false.

所以,基本上,考虑到我需要生成作为参数传递给我当前无法更改的预先存在的函数的函数.如何动态生成这些函数?

So, basically, given that I need to generate functions that are passed as arguments to a pre-existing function that I cannot change currently. How can I dynamically generate these functions?

推荐答案

尝试使用 IIFE:

for (var i = 0; i < fNames.length; i += 1)
{
    (function(i){
        trace("Creating function with indice = ", i);
        funcs.push(
            function() : void 
            {
                saveGame(fNames[i]);
            }
        )
    })(i);
}

这篇关于使用定义时定义的参数创建一组匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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