The value of 'a' seems to lose global scope when the constructor a is called.

var a = 6;

function b() {
    a = 10;

    function a() {}
    console.log(a); //10
}
b();
console.log(a); //6
有帮助吗?

解决方案

The order is interpreted as shown below due to variable hoisting. Note that as @ShadowCreeper correctly points out, function a(){} is actually creating a local variable a inside of function b which is hoisted as shown below.

var a;
var b;

a = 6;
b = function() {
 var a;
 a = function(){};
 a = 10;
 console.log(a); //10
}
b();
console.log(a); //6

其他提示

Because you are creating a local variable (the function a) then replacing that local variable's value (the function) with 10.

One way to avoid things like this is to precede all local variables and functions with "_" (underscore).

This answer has a really nice explanation of what is going on here.

The summary is that Javascript is processed in two phases, compilation and then execution. The function definitions occur during the compilation step, so inside of b the compiler sees the definition function a() {} and the local variable a is created within the scope of b. Later on when the code is executed, the scope of b already contains the local variable a before any code is executed, so the line a = 10; is just giving the local variable a new value. The function definition was already processed during compilation so that will not happen during execution, so console.log(a) will output 10.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top