外部函数的变量不可修改

时间:2012-05-29 18:29:06

标签: javascript function variables scope

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

// 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??            
​

1 个答案:

答案 0 :(得分:2)

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