[英]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. 尽管Stackexchange Meta禁止我以“嗨”开头,但我认为友好并不会对您造成实质性伤害。
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. 但是JSLint警告我,在循环内定义函数将是一种不好的做法。
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
. 这导致
Uncaught ReferenceError: error is not defined
。 How can I not redefine a function, but still passing the error
as in the original function(error){...}
? 如何不重新定义函数,但仍像原始
function(error){...}
一样传递error
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
). ready
需要一个函数对象,因此您必须传递chechLogin
本身而不是调用它并传递其返回值(可能是undefined
)。
How can I not redefine a function, but still passing the
error
as in the originalfunction(error){...}
?如何不重新定义函数,但仍像原始
function(error){...}
一样传递error
function(error){...}
?
Maybe that's where the confusion lies. 也许这就是混乱所在。 You are actually not passing
error
at all. 您实际上根本没有传递
error
。 The argument is passed by the caller , which is ready
. 该参数由已
ready
调用方传递。
One nice feature of JavaScript is that you can simple replace variables with the literal representation of their value (in most cases). JavaScript的一个不错的功能是,您可以用变量的值的文字表示形式简单地替换变量(在大多数情况下)。
So if we look at 所以如果我们看
new Magister(...).ready(checkLogin(error));
and replace checkLogin
with it's value (the function) it becomes 并用它的值(函数)替换
checkLogin
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. 突然在我们的函数定义的末尾出现了一个野
(error)
。
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. 好多了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.