当我把userName和password参数传给setTimeout函数时,为什么我得到{ userName: undefined, password: undefined }作为最终输出?我从setTimeout函数中删除了它们,然后我得到了预期的输出。
console.log("Starting");
displayUser = (userName, password, callback) => {
console.log("Iam inside the displayUser function")
setTimeout((userName, password) => {
console.log("Iam inside the setTimeOut function");
callback({
userName: userName,
password: password
});
}, 3000)
}
displayUser("Hasindu", "hasindu123", (user) => {
console.log("Iam inside the call back function");
console.log(user);
});
console.log("end");
回调函数采取 username
和 password
参数,但你永远不会将它们作为参数传递。
你可以给 setTimeout
这些变量将作为参数传递给回调。
console.log("Starting");
displayUser = (userName, password, callback) => {
console.log("Iam inside the displayUser function")
setTimeout((userName, password) => {
console.log("Iam inside the setTimeOut function");
callback({
userName: userName,
password: password
});
}, 3000, userName, password)
}
displayUser("Hasindu", "hasindu123", (user) => {
console.log("Iam inside the call back function");
console.log(user);
});
console.log("end");
或者你也可以不输入参数,变量将被保存在闭包中。
console.log("Starting");
displayUser = (userName, password, callback) => {
console.log("Iam inside the displayUser function")
setTimeout(() => {
console.log("Iam inside the setTimeOut function");
callback({
userName: userName,
password: password
});
}, 3000)
}
displayUser("Hasindu", "hasindu123", (user) => {
console.log("Iam inside the call back function");
console.log(user);
});
console.log("end");
你的 setTimeout
回调是影子的 userName
和 password
变量。您可以将它们从 setTimeout
回调或将它们作为参数添加到 setTimeout
这样叫。
setTimeout((userName, password) => {
console.log("Iam inside the setTimeOut function");
callback({
userName: userName,
password: password
});
}, 3000, userName, password)