同名的函数和变量 [英] Function and variable with the same name
问题描述
下面的代码片段是一个测试,看看当一个函数和一个变量在同一范围内共享相同的名称时会发生什么.在 Chrome 中,变量定义似乎具有优先权.
The following code-snippet is a test to see what happens when a function and a variable share the same name in the same scope. In Chrome it appears the variable definition has precedence in reference.
- 命名的函数可以被执行,还是被变量声明完全遮住了?
- 变量优先于同名函数是 Javascript 中的标准行为吗?
抱歉问了两部分的问题,但问两个单独的问题似乎很浪费.
Sorry for the two part question, but it seemed wasteful to ask two separate questions.
代码:
<!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 中,函数定义被提升到当前作用域的顶部.因此,您的示例代码如下:
In JavaScript, function definitions are hoisted to the top of the current scope. Your example code therefore reads as:
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-范围和提升
This is some good read about this topic: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
这篇关于同名的函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!