[英]Basic JavaScript, why is this function not passing the parameter
I'm trying to learn JavaScript coming from C#.我正在尝试学习来自 C# 的 JavaScript。 I wrote this simple code but for some reason, the parameter is not being passed to the setTimeout function.
我写了这个简单的代码,但由于某种原因,参数没有传递给 setTimeout 函数。
function displayName(name) {
console.log(`Name is ${ name }`);
}
function login(name) {
// The argument 'name' is not being passed from the login function to the setTimeout !!
setTimeout(name =>{
displayName(name)
}, 2000);
}
login("Satoshi")
I expect the output to be: Name is Satoshi
我希望输出是:
Name is Satoshi
Instead I get: Name is undefined
相反,我得到:
Name is undefined
Where am I going wrong?我哪里错了? There's clearly something I am not understanding about JavaScript parameters and scope.
很明显,我对 JavaScript 参数和范围有一些不了解。
The argument 'name' is not being passed from the login function to the setTimeout !!
参数“名称”没有从登录函数传递给 setTimeout !!
That's because you're shadowing the login
name
parameter with the parameter to your arrow function.那是因为您使用箭头函数的参数隐藏了
login
name
参数。 A parameter name in a function parameter list is similar to a variable declaration within the function body, so your original code has an outer name
(in login
) and a separate inner one (in the arrow function).函数参数列表中的参数名称类似于函数体内的变量声明,因此您的原始代码具有外部
name
(在login
)和单独的内部name
(在箭头函数中)。 The innermost one is the one that gets used when you use the name of the parameter (or variable).最里面的一个是当您使用参数(或变量)的名称时使用的那个。
Replace name
with ()
in the arrow function so it doesn't declare its own name
parameter;将箭头函数中的
name
替换name
()
,这样它就不会声明自己的name
参数; then it will close over the name
parameter in login
:然后它将关闭
login
的name
参数:
function login(name) {
setTimeout(() =>{
// −−−−−−−−−−−−^^
displayName(name);
}, 2000);
}
By default, setTimeout
on browsers doesn't call the function you give it with any arguments, so the name
parameter in the arrow function in your original code would always have the value undefined
.默认情况下,浏览器上的
setTimeout
不会使用任何参数调用您提供的函数,因此原始代码中箭头函数中的name
参数将始终具有值undefined
。
In some situations you may want setTimeout
to pass an argument or arguments to the timer callback when calling it, which you do by passing those after the timeout interval, like this:在某些情况下,您可能希望
setTimeout
在调用时将一个或多个参数传递给计时器回调,您可以通过在超时间隔之后传递这些参数来实现,如下所示:
function login(name) {
setTimeout(innerName =>{
// ^^^^^^^^^−−−−−−−− the arrow function's parameter
displayName(innerName);
// ^^^^^^^^^−−− using the arrow function's parameter's value
}, 2000, name);
// ^^^^−−−−−−−−−−−−−−− `login`'s `name`
}
But there's no need for that in your example.但是在您的示例中不需要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.