简体   繁体   中英

Javascript - Replace callback with function, including parameters

Though Stackexchange Meta forbids me to start with "Hi,", I think there is no substantial harm to being friendly.

Hi,

I use the following piece of code,

while (!success) {
    new Magister(chosenSchool, username, password).ready(function(error){
        /* Code here using the error variable above */
    });
}

but JSLint warnes me that it would be a bad practice to define functions inside a loop.
However, using the following code, doesn't work either.

function checkLogin(error) {
    /* Code here using the error variable above */
}
while (!success) {
    new Magister(chosenSchool, username, password).ready(checkLogin(error));
}

This results into Uncaught ReferenceError: error is not defined . How can I not redefine a function, but still passing the error as in the original function(error){...} ?
I tried various methods, but it won't budge for me.

Thanks in advance!

Just don't call the function:

new Magister(chosenSchool, username, password).ready(checkLogin);

ready expects a function object, so you have to pass chechLogin itself instead of calling it and passing its return value (which is likely undefined ).

How can I not redefine a function, but still passing the error as in the original function(error){...} ?

Maybe that's where the confusion lies. You are actually not passing error at all. The argument is passed by the caller , which is ready .


One nice feature of JavaScript is that you can simple replace variables with the literal representation of their value (in most cases).

So if we look at

new Magister(...).ready(checkLogin(error));

and replace checkLogin with it's value (the function) it becomes

new Magister(...).ready(function checkLogin(error){...}(error));

However, that doesn't look like the first version at all! Suddenly a wild (error) appears at the end of our function definition.

Lets go the other way round:

new Magister(...).ready(function(error){...});
// becomes
new Magister(...).ready(function checkError(error){...});
// becomes
function checkError(error) { ... }
new Magister(...).ready(checkError);

Much better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM