创建一组匿名函数在definiton时间定义的参数 [英] Create a set of anonymous functions with parameters defined at definiton time
问题描述
我试图逐步重构现有的code。我有一组的功能定义的,并且只相差的内部参数之一:
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] ...);
不过,据我所知,封闭导致的状态,我
来维持超出了范围的循环,任何试图调用任何的生成功能未能与越界的错误,这是你所期望给什么我
将达到 fNames.size + 1
在 I&LT; fNames.size
的计算结果为假。
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.
所以,基本上,因为我需要生成作为参数传递到pre-现有的功能,我目前还不能更改的功能。如何动态生成这些功能呢?
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?
推荐答案
尝试使用的生活to :
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);
}
这篇关于创建一组匿名函数在definiton时间定义的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!