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

查看:477
本文介绍了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函数执行另一个回调函数,它的工作原理: p>

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.

这两个选项如下: p>

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天全站免登陆