以下代码片段是一个测试,用于查看函数和变量在同一范围内共享同一名称时会发生什么.在Chrome中,似乎变量定义在引用中具有优先权.
>命令函数可以执行,还是被变量声明完全遮盖?
> Javascript中的标准行为是变量优先于具有相同名称的函数吗?
对于这两个问题很抱歉,但问两个问题似乎很浪费.
码:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var overlapping = function() { return 'this is a var holding an anonymous function' };
function overlapping()
{
return 'this is a function definition';
}
output( overlapping, 'overlapping' );
output( overlapping(), 'overlapping()' );
function output( expression, description )
{
document.writeln( '<li>' + ( description ? ('<i>' + description + '</i>: ') : '' ) + expression + '</li>' );
}
</script>
</body>
</html>
解决方法:
在JavaScript中,函数定义被提升到当前范围的顶部.因此,您的示例代码如下:
var overlapping = function() { return 'this is a function definition' };
var overlapping = function() { return 'this is a var holding an anonymous function' };
这是关于这个主题的一些很好的阅读:http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting