我发现自己是通过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());
Run Code Online (Sandbox Code Playgroud)
输入我得到我的日志:
false
does work
Run Code Online (Sandbox Code Playgroud)
另外我想知道如何做类似于第一个例子,
干杯,戴夫.
javascript ×1