这个例子展示了变量和函数的命名及其作用域在 JavaScript 中的重要性。考虑以下代码...
a = a();
console.log('typeof global variable a :',(typeof a));
function a() {
console.log('A');
a = function() {
console.log('B');
};
console.log('typeof global function a() inner function a() :',(typeof a));
}
console.log('typeof global function a() :',(typeof a));
a();
//=> ! TypeError: a is not a function
//=> A
//=> typeof global function a() inner function a() : function
//=> typeof global variable a : undefined
//=> typeof global function a() : undefined
那么发生了什么?
function a() 的内部变量a 返回其类型:function
全局变量a被设置为function a()的返回值——但是函数没有返回任何东西所以它自动变成undefined
全局 function a() 的类型仍然由值 a 'outside' 决定(可以这么说) - undefined
注意到对console.log() 的调用的到达顺序了吗?
不仅内部a没有设置var,自动将其置于全局范围内,而且a = a()意味着它甚至不再是一个函数!
是a = a() 导致a is not a function TypeError。
另一方面,看看当我删除 a = 时会发生什么,但保留其他所有内容...
a();
console.log('typeof global variable a :',(typeof a));
function a() {
console.log('A');
a = function() {
console.log('B');
};
console.log('typeof global function a() inner function a() :',(typeof a));
}
console.log('typeof global function a() :',(typeof a));
a();
//=> A
//=> typeof global function a() inner function a() : function
//=> typeof global function a() : function
//=> typeof global variable a : function
//=> B
看看顺序有什么变化?
我们现在不能将“全局变量 a”(和以前一样)视为一个变量 - a 只是一个指向函数的标记。
function a() 被调用,触发console.log(A),将令牌a(它本身)重置为新函数,然后在再次调用时触发console.log(B)。
可以从中挤出更多细节,以及实现相同结果的更好方法,但对控制台的调用是了解正在发生的事情的重要线索。不要将示例视为可用的模式 - 将其视为暗示 JavaScript 引擎如何执行其工作的东西。
您可能会发现来自 JavaScriptIsSexy.com 的这篇文章很有用:JavaScript Variable Scope and Hoisting Explained