我正在调用如下所示的函数。在这里,我还传递了回调函数,该函数只能在特定表单提交之后调用,而不是在此之前调用。
<div onClick="myNamespace.openDialog(par1,par2,myNamespace.callback(myNamespace.cb,'p1','p2'))">OPEN DIALOG</div>
var myNamespace = myNamespace || {};
myNamespace={
return{
cb:function(p1,p2){alert(p1+" cb "+p2);},
callback:function(f){f(arguments[1],arguments[2]);},
openDialog:function(p1,p2,f){
// aboutBizzNs.cb should be called here only after form submit
}
}
}();
问题是在单击OPEN DIALOG
后立即调用alert(p1+"cb "+p2);
。不应该是这样的。应该只在我想要的时候调用它。有什么问题
最佳答案
问题是 aboutBizzNs.callback
立即调用作为参数提供的函数。
与以下创建并返回 closure (function) 的内容进行比较它将调用在调用它本身时提供的函数:
callback: function(f){
// The f variable is bound in a closure below, which is returned immediately.
// However, the f function is NOT invoked yet.
// We also copy the arguments of this function invocation and expose
// them via a variable which is also bound in the following closure.
var boundArgs = Array.prototype.slice(arguments, 0);
return function () {
// Now f is invoked when this inner function is evaluated, which
// should be in response to the event.
return f(boundArgs[1], boundArgs[2]);}
}
}
我还会使用apply
,如下所示,可以使用任意数量的“绑定(bind)”参数..
return function () {
return f.apply(this, boundArgs.slice(1));
}
..但是这是一个相当常见的操作,并且已经被 Function.prototype.bind
支持。 (这是 ES5 的一部分,并且可以在其他浏览器中进行填充)。因此,原来的..
myNamespace.callback(myNamespace.cb,'p1','p2')
..可以写成..
myNamespace.cb.bind(this,'p1','p2')
..在这里达到同样的效果。不同之处在于回调 (cb
) 函数内的 this
可能有所不同,因为 bind
不允许“传递”这个
。
或者,忘记所有这些特殊函数并简单地包装回调..
function () { myNamespace.cb('p1','p2') }
关于javascript - 将回调函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594372/