gpt4 book ai didi

javascript - 变量如何在 Javascript 中工作?在 setTimeout 期间变量值可以改变吗?

转载 作者:行者123 更新时间:2023-11-29 20:07:11 24 4
gpt4 key购买 nike

我有以下代码:

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 内的函数时(第二次调用 Notification 已经使用 type = "error"),它会将变量“type”视为“error”,即使这是第一个调用,它是用 type = "success"调用的吗?

最佳答案

if the function Notification gets called on a click event, and if it gets called two times (first with Notification("success") then with Notification("error")) by two click events, is it possible that the second function call changes the type variables value for the first function call?

没有。 type 变量是一个参数,因此范围绑定(bind)到您的函数。它的值在后续调用中不会改变,每个函数调用都会创建该变量的一个新实例并且无法访问其他实例。

您的超时匿名函数的作用域是Notification 作用域的“子作用域”,因此它将始终访问正确的type 变量。

但是您的 notificationID 是一个全局变量(不是本地范围的),所有对 Notification 的调用和所有超时都将使用相同的变量实例。因此,第二次调用 Notification 会在第一次访问超时之前更改它。要解决此问题,请添加 var 关键字。

或者,由于 setNotificationTimeoutId 也在外部范围内并且可以从两个调用访问,您可以(应该?)通过添加以下行在创建新超时之前清除所有事件超时:

clearTimeout(setNotificationTimeoutId);

关于javascript - 变量如何在 Javascript 中工作?在 setTimeout 期间变量值可以改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com