gpt4 book ai didi

javascript - 外部函数中的变量不可修改

转载 作者:行者123 更新时间:2023-12-02 19:37:14 26 4
gpt4 key购买 nike

如果我在外部函数中有一个变量,并且有一个更改该变量的内部函数,为什么该变量会恢复到其原始值?

// Check which type of event registration browser supports
function addEvent(eventTarget, eventType, eventHandler){
if (window.addEventListener){
eventTarget.addEventListener(eventType, eventHandler);
}
else if (window.attachEvent){
var eventType = "on" + eventType;
eventTarget.attachEvent(eventType, eventHandler);
}
}

// Check if browser supports DOMContentLoaded
var DOMContentLoadedSupported = "no";

addEvent(document, "DOMContentLoaded", function(){
DOMContentLoadedSupported = "yes";
})

alert(DOMContentLoadedSupported) // alerts "no" not "yes". Why??

最佳答案

该函数将修改变量,但这将在您发出警报之后发生,因此您会在警报中看到“否”,因为警报发生在变量被修改之前。

关于javascript - 外部函数中的变量不可修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10804666/

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