我发现自己在 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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)