我有以下代码:
function Notification(type)
{
switch (type)
{
case "success":
notificationID="not1";
break;
case "error":
notificationID="not2";
break;
}
setNotificationTimeoutId = setTimeout(function () {
jQuery('#' + notificationID).fadeOut(200, function () {
var notification = document.getElementById(notificationID);
if (notification)
{
jQuery(notification.parentNode).remove();
if (type == "success")
DoSomething();
}
setNotificationTimeoutId = null;
});
}, 5000);
}
我的问题是,如果函数(Notification)在点击事件上被调用,并且如果它被两次点击事件调用两次(第一次是Notification(“success”),然后是Notification(“error”)),第二个函数调用是否有可能更改第一个函数调用的类型变量值?
例如:当第一次调用(一次成功)进入 setTimeout 内的函数(已使用 type =“error”对通知进行第二次调用)时,它会将变量“type”视为“错误”,即使这是第一个调用,并且是用 type = "success"调用的?
最佳答案
if the function
Notification
gets called on a click event, and if it gets called two times (first withNotification("success")
then withNotification("error")
) by two click events, is it possible that the second function call changes thetype
variables value for the first function call?
没有。 type
变量是一个参数,因此其作用域仅限于您的函数。它的值在后续调用中不会改变,每个函数调用都会创建该变量的一个新实例,并且无法访问其他变量。
用于超时的匿名函数的作用域是Notification
的“子作用域”,因此它将始终访问正确的type
变量。
但是您的 notificationID
是一个全局变量(不是局部范围的),对 Notification
的所有调用以及所有超时都将使用同一个变量实例。因此,第二次调用 Notification
会在第一次访问超时之前更改它。要解决此问题,请添加 var
关键字。
或者,由于 setNotificationTimeoutId
也在外部作用域中,并且可以通过两个调用进行访问,因此您可以(应该?)在创建新超时之前清除所有事件超时,方法是添加以下行:
clearTimeout(setNotificationTimeoutId);
关于javascript - 变量在 JavaScript 中如何工作? setTimeout期间变量值可以改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540698/