2012-02-22 41 views
0

我发现自己的Javascript的变量范围,有人可以向我解释为什么第一个示例不起作用,但第二个呢?由Javascript的变量范围迷惑

function test() { 
    return typeof(the_variable) !== 'undefined' && the_variable; 
} 

(function() { 
    var the_variable = "doesn't work"; 
    console.log(test()); 
}()); 

var the_variable = "does work"; 
console.log(test()); 

输出我在日志中得到:

false 
does work 

我也想知道怎么做类似于第一个例子中的东西,

干杯,戴夫。

回答

6

解释评论:

function test() { 
    return typeof(the_variable) !== 'undefined' && the_variable; 
} 

// The variable in this function is scoped to the anonymous function. 
// It doesn't exist outside that function, so `test` cannot see it 
(function() { 
    var the_variable = "doesn't work"; 
    console.log(test()); 
}()); 

// This variable exists in a scope that wraps the `test` function, so it can see it. 
var the_variable = "does work"; 
console.log(test()); 
+0

但测试函数被调用匿名函数的范围内,为什么不能测试看到匿名函数的范围里面的东西? – kzar 2012-02-22 17:26:24

+0

更明确地说,把'var foo'放在一个范围内的任何地方都完全等同于把它作为范围内的第一项。 – gsnedders 2012-02-22 17:27:31

+2

@kzar因为它不是调用链范围,所以它是词法范围。 – gsnedders 2012-02-22 17:28:05

0

在JavaScript中,函数定义范围。在您的第一个示例中,the_variable不在test的范围之内。另一方面,在第二个示例中,the_variable在全局范围内定义并且在任何地方都可用。

编辑

捕捉the_variable在闭合,如果你希望它是提供给test

var foo = (function() { 
    var the_variable = "does work"; 
    function test() { 
     return typeof(the_variable) !== 'undefined' && the_variable; 
    } 
    return {test : test}; 
}()); 
console.log(foo.test()); 

输出:

确实工作

+0

对,但如果我从另一个函数内调用一个函数,为什么调用的函数不能访问它被调用的地方? – kzar 2012-02-22 17:29:45

+0

'function test()'打开一个新的范围。来自封闭匿名函数的'var'将不可用。如果可用,则在闭包中捕获'the_variable'。 – 2012-02-22 17:40:18

+0

很酷的主意,但我不能在闭包内定义test()函数,闭包实际上是在一个单独的文件中定义的。 – kzar 2012-02-22 17:47:09