Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...