函数作用域在JavaScript中是如何工作的?

函数作用域在JavaScript中是如何工作的?,javascript,Javascript,JavaScript中的函数作用域是如何工作的 // Create a new function = new scope (function() { var a = 1; // create a new variable in this scope if (true) { // create a new block var a = 2; // create "new" variable with same name, //

JavaScript中的函数作用域是如何工作的

// Create a new function = new scope
(function() {
    var a = 1; // create a new variable in this scope

    if (true) { // create a new block
        var a = 2; // create "new" variable with same name,
                   // thinking it is "local" to this block
                   // (which it isn't, because it's not a block scope)
    }

    alert(a); // yields 2 (with a block scope, a would still be 1)
})();

alert(typeof a); // yields "undefined", because a is local to the function scope above

试试看:

非常棒的例子,正是我需要得到的+1.感谢这个有效的工具——JSFIDLE。