带参数的Javascript回调函数 [英] Javascript callback function with parameters

查看:18
本文介绍了带参数的Javascript回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题看起来像是重复的,因为标题几乎是重复的.但是,我的问题似乎更简单,我找不到答案.

This question looks like a duplicate, as the title is nearly replicated. But, my issue seems simpler and I can't find the answer to it.

我有一个执行另一个回调函数的 Javascript 函数,它的工作原理是这样的:

I have a Javascript function that executes another callback function, it works like this:

<script type='text/javascript'>
firstfunction(callbackfunction);
</script>

其中回调函数定义为:

callbackfunction(response) {
    if (response=='loggedin'){
    // ... do stuff
}}

但我希望它是这样的:

callbackfunction(response, param) {
    if (response=='loggedin'){
    // ... do stuff with param
}}

我的问题是,像这样传递参数是否有效:

My question is, does it work to pass the parameter like this:

<script type='text/javascript'>
firstfunction(callbackfunction(param));
</script>

还是我做错了?

推荐答案

直接回答你的问题,这不起作用:

In direct answer to your question, this does not work:

 firstfunction(callbackfunction(param));

这将立即执行 callbackfunction 并将执行它的返回值作为参数传递给 firstfunction 这不太可能是你想要的.

That will execute callbackfunction immediately and pass the return value from executing it as the argument to firstfunction which is unlikely what you want.

从你的问题中不清楚你是否应该改变 firstfunction() 在它调用回调时将两个参数传递给 callbackfunction() 或者你是否应该做一个使用参数调用回调函数的匿名函数.

It is unclear from your question whether you should just change firstfunction() to pass two parameters to callbackfunction() when it calls the callback or whether you should make an anonymous function that calls the callback function with arguments.

这两个选项看起来像这样:

These two options would look like this:

function firstfunction(callback) {
    // code here
    callback(arg1, arg2);
}

firstfunction(callbackfunction);

function firstfunction(callback) {
    // code here
    callback();
}

firstfunction(function() {
    callbackfunction(xxx, yyy);
});

这篇关于带参数的Javascript回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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