这里是一些示例代码:
function DoStuff()
{
var v1 = $('#htmlControl1').val();
var v2 = $('#htmlControl2').val();
myFunction1(v1, v2, (myFunction2(v1, v2, myFunction3)));
}
function myFunction1(v1, v2, completeFunc1)
{
//ajax code here, using jQuery, that calls
//'completeFunc1' in the 'complete:' block
}
function myFunction2(v1, v2, completeFunc2)
{
//ajax code here, using jQuery, that calls
//'completeFunc2' in the 'complete:' block
}
function myFunction3()
{
//performs some other tasks
}
意图是myFunction1
将被调用,将进行 ajax 调用,完成后将调用 myFunction2
这又会做同样的事情,调用 myFunction3
完成后。
实际结果是myFunction2
首先被调用,执行myFunction3
完成后,返回null
。 myFunction1
然后用 null
调用作为完整函数的参数,导致在完成时不执行任何操作(我在那里进行了空检查,所以这不是问题)。
那么,我该如何做我想要的事情呢?如何正确通过myFunction2(v1, v2, myFunction3)
,使用给定的变量,到 myFunction1
作为一个论点?
最佳答案
新奇的 JavaScript 环境和各种库(原型(prototype)、功能)提供了一个“绑定(bind)”API,给定一个函数(“f”)和一些参数,它会返回一个函数,在调用时,该函数将调用“f”您选择的this
值和您选择的参数:
var bound = myFunction.bind(something, v1, v2, myFunction3);
现在,打电话
bound();
完全一样
myFunction.call(something, v1, v2, myFunction3);
有时人们称其为“柯里化(Currying)”,但这实际上不是真正的柯里化(Currying),因为值在调用“bind()”时全部绑定(bind)。尽管如此,它仍然有用且简洁。根据您想要的效果,“bind()”非常容易实现;我建议查看Functional.js source code并从那里开始。 jQuery 版本称为 $.proxy()
但它相对蹩脚(无法绑定(bind)参数)。
关于javascript - 如何将带有非静态参数的函数作为 JavaScript 中的变量传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716266/