JavaScript的:是否有可能通过一个可变进分配给变量的回调函数?有可能、回调、变量、函数

2023-09-10 14:17:30 作者:雨落青衣

很多人说这是问的意见,这让我迟疑地问这太多了,但我还没有发现他们的答案的解决方案,主要是因为(1)它们通常使用jQuery和( 2)这些问题通常包括技术问题,我不明白。

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.

我有一个变量中的功能。变量被分配的功能。我敢肯定,这个概念是不是唯一到AJAX,但是这是我使用它的背景下,如果它的确与众不同。

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.

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?

推荐答案

只是不声明变量作为参数,在匿名函数,像这样的:

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); }
}

当您拨打的第一个参数这是无论是的呼叫的该回调传入这就是里面的函数。如果您想引用previously声明的变量只是做到这一点,要确保的没有的使用参数具有相同的名称。

When you call the first parameter foo it's whatever's calling that callback passes in that's foo inside the function. If you want to reference a previously declared variable just do that, make sure not to use a parameter with the same name.

 
精彩推荐
图片推荐