JavaScript:是否可以将变量传递给分配给变量的回调函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3946177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:47:40  来源:igfitidea点击:

JavaScript: Is it possible to pass a variable into a callback function that is assigned to a variable?

javascriptajax

提问by Tarik

A lot of people say that this is asked too much in the comments, which made me hesitant to ask this, but I still have not found a solution in their answers, mostly because (1) they are typically using jQuery and (2) the questions usually contain technicalities I do not understand.

很多人说评论中问的太多了,这让我犹豫要不要问这个,但我仍然没有在他们的答案中找到解决方案,主要是因为(1)他们通常使用 jQuery 和(2)问题通常包含我不明白的技术细节。

I have a function with a variable inside. The variable is assigned a function. I'm sure this concept is not exclusive to AJAX, but that is the context I am using it in, if it makes a difference.

我有一个函数,里面有一个变量。变量被分配了一个函数。我确信这个概念不是 AJAX 独有的,但如果它有所不同,那就是我使用它的上下文。

function iClick(this)
{
    var foo = "I would like to pass this.";

    ajax.onreadystatechange = function (foo) { alert(foo); }
}

I want to pass a variable into the function. However, since there is no original function declaration, how do I specify parameters? Can I even do that?

我想将一个变量传递给函数。但是,由于没有原始函数声明,我该如何指定参数?我什至可以这样做吗?

回答by Nick Craver

Just don't declare that variable as a parameter in your anonymous function, like this:

只是不要在匿名函数中将该变量声明为参数,如下所示:

function iClick(this)
{
    var foo = "I would like to pass this.";
    ajax.onreadystatechange = function () { alert(foo); }
}

When you call the first parameter fooit's whatever's callingthat callback passes in that's fooinside the function. If you want to reference a previously declared variable just do that, make sure notto use a parameter with the same name.

当您调用第一个参数时,foo它是回调传入的函数内部的任何调用foo。如果您想引用先前声明的变量就这样做,请确保不要使用具有相同名称的参数。

回答by John Hartsock

You can create a function like this

您可以创建这样的函数

var c="hello";

(function(b){
   alert(b) 
})(c);

result would be "hello"

结果将是“你好”

回答by Claudiu

You can also do this, but maybe it's not necessary:

您也可以这样做,但也许没有必要:

function iClick(this)
{
    var foo = "I would like to pass this.";

    ajax.onreadystatechange = (function(thevar) {
        return function () { alert(thevar); };
      })(foo);
}

回答by Jo?o Pimentel Ferreira

As @John Hartsock referred, the answer that everyone should really remember is this

正如@John Hartsock 所提到的,每个人都应该真正记住的答案是这个

var c="hello";

(function(b){
   alert(b) 
})(c);

And that's very important for example in a forloop when there is some async function inside it, because otherwise you don't get the correct item.

这非常重要,例如在for循环中,当其中有一些异步函数时,否则您将无法获得正确的项目。

Tell me, what comes out from here?

告诉我,从这里出来的是什么?

for (var i=0; i<5; i++){
  setTimeout(function(){ 
    console.log(i); 
    }, 1000);
}

Exactly: all 5, because when all the timers are triggered after 1 second, variable iis already at the value 5.

完全正确:全部 5 个,因为当所有计时器在 1 秒后触发时,变量i已经为值5

But if you use a self-invoked anonymous function(SIAF) like this

但是如果你使用像这样的自调用匿名函数(SIAF)

for (var i=0; i<5; i++){
  (function (j){
    setTimeout(function(){ 
      console.log(j); 
      }, 1000);
   })(i);
}

it does work, since every time the function is evoked, it runs another instance of the function and as any function, it has its own local variables. I do not merely define the function, I also run it right away (through the ();at the end), but then internally a new instance of the function will be created with different internal local variables, as I parse to the function a different variable every time I run it.

它确实有效,因为每次调用该函数时,它都会运行该函数的另一个实例,并且与任何函数一样,它都有自己的局部变量。我不仅定义了函数,我还立即运行它(通过();最后),但是然后在内部创建一个具有不同内部局部变量的函数的新实例,因为我每次解析到函数一个不同的变量时间我运行它。

回答by vittore

I belive you wanted something like that

我相信你想要那样的东西

function handleAjaxRequest(params) {
    var context = {'b':'inner', 'c': params['c']};
    function rendered(html) {
      // render
    }
    function gotPart(part) {
        context['a'] = part;
        engine.render(context).addCallback(rendered);
    }
    ajax.getPart(params).addCallback(gotPart);
}