Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 741
Tarik Avatar asked Oct 15 '10 21:10

Tarik


People also ask

Can a callback function take parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn);

Can a callback function return a value in JavaScript?

A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value. Yes, it makes fun sense to try and return a value from a promise callback.


2 Answers

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.

like image 153
Nick Craver Avatar answered Sep 18 '22 13:09

Nick Craver


You can create a function like this

var c="hello";  (function(b){    alert(b)  })(c); 

result would be "hello"

like image 28
John Hartsock Avatar answered Sep 18 '22 13:09

John Hartsock