【发布时间】:2016-06-05 14:21:38
【问题描述】:
如果我有-
function outer(){
function inner(){}
}
inner 在outer 之外不可见
但如果我有这样的东西-
if (true) { // the scope for foo starts here
function foo() {
return 'first';
}
// the scope for foo ends on the } in next line
}
else {
function foo() {
return 'second';
}
}
那么,
typeof foo == function // true, foo is visible here, Why?
【问题讨论】:
-
否
foo的范围不会启动 if 块。除了let,js 没有块作用域,而是基于函数的作用域。除此之外,这不是在 if 块中定义函数的有效语法。 -
一个函数本身就是一个“作用域”,它里面的所有东西都不会从它里面流出,但是它可以访问函数之外的全局变量。 foo.Prototype.bar = function () {} 可以扩展 foo 函数。您使用的示例始终声明函数,它始终为真或假。
-
JavaScript 不是块作用域,而是函数作用域。 “foo 的范围在下一行的 } 结束”是完全错误的。
标签: javascript