被Javascript搞糊涂了';s变量范围

被Javascript搞糊涂了';s变量范围,javascript,Javascript,我发现自己被Javascript的变量作用域所困扰,有人能解释一下为什么第一个例子不起作用,而第二个却起作用吗 function test() { return typeof(the_variable) !== 'undefined' && the_variable; } (function () { var the_variable = "doesn't work"; console.log(test()); }()); var the_

我发现自己被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
我还想知道如何做与第一个示例类似的事情。

在评论中解释:

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());
评论中解释:

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());

在Javascript中,函数定义作用域。在第一个示例
中,_变量
不在
test
的范围内。另一方面,在第二个示例中,
_变量
在全局范围内定义,并且在任何地方都可用

编辑

如果希望该变量可用于
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());
输出:


在Javascript中,函数定义作用域。在第一个示例
中,_变量
不在
test
的范围内。另一方面,在第二个示例中,
_变量
在全局范围内定义,并且在任何地方都可用

编辑

如果希望该变量可用于
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());
输出:

确实有效

函数测试()
打开一个新范围<封闭匿名函数中的code>var
将不可用。在闭包中捕获
变量,如果该变量可用。
函数测试()
打开一个新范围<封闭匿名函数中的code>var
将不可用。捕获闭包中的_变量(如果该变量可用)。