JavaScript回调函数不处理传递参数

时间:2012-05-24 15:02:14

标签: javascript callback

我一直在撞墙挡住这一点,我似乎无法弄明白。我知道那里有很多其他非常相似的问题,而且我已经看了几乎所有这些问题,而且他们似乎都找不到我正在寻找的答案(但话又说回来,我可能会失明今天)。

所以我有一个JavaScript函数,我将函数作为参数传递来进行回调。我的函数中有一个参数,所以当我进行回调时,我传入的参数需要在调用回调时完成。

但是,当我添加第二个参数时,该值始终未定义。

示例代码:

<div style="padding: 15px;">
<a href ="#" onclick="FirstFunction('first param');">test</a>
</div>

//call the first function from the click event and pass in the value
function FirstFunction(param1) {
    //call my process function, but pass in a function as a parameter with the value from param1
    myProcessFunction(function(){SecondFunction(param1)});
    return false;
}

function SecondFunction(param1, param2) {
    alert(param1 + ', ' + param2);
}

function myProcessFunction(callback) {
    if (typeof callback == 'function') {
        //call my passed in function, return the original values, along with a new value into my "SecondFunction"
        callback(this, 'second param');
    }
}

任何帮助将不胜感激。

我试过了:

callback.call(this, 'param 2')

callback(arguments, 'param 2')

callback.call(arguments, 'param 2')

可能还有大约20种其他组合......所以我现在正在猜测。

这是我的jsFiddle:

http://jsfiddle.net/FVsDK/8/

修改

谢谢Jani,这是jsFiddle中的一个有效解决方案: http://jsfiddle.net/FVsDK/9/

1 个答案:

答案 0 :(得分:3)

错误是由于你的回调有点混乱引起的:)

myProcessFunction(function(){SecondFunction(param1)});

这使用回调函数function() { ... }

调用myProcessFunction

因此,在myProcessFunction中,callback(this, 'second param');正在调用上面的函数,它根本不需要任何参数。

如果你想让secondFunction从myProcessFunction获取参数,你必须传递它而不是你的匿名回调:

myProcessFunction(SecondFunction)

此处,SecondFunction的参数为this'second param'

或者如果你想将param1传递给它,你也可以这样做:

myProcessFunction(function(a, b) { SecondFunction(param1, a, b); })

此处,SecondFunction的参数将是param1,this'second param'的值。

相关问题