[英]Function and variable with the same name
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.在 Chrome 中,变量定义似乎在引用中具有优先权。
Sorry for the two part question, but it seemed wasteful to ask two separate questions.很抱歉有两个部分的问题,但问两个单独的问题似乎很浪费。
Code:代码:
<!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>
In JavaScript, function definitions are hoisted to the top of the current scope.在 JavaScript 中,函数定义被提升到当前作用域的顶部。 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' };
This is some good read about this topic: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting这是关于这个主题的一些很好的阅读: http : //www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Can the named function be executed, or is it completely obscured by the variable declaration?是否可以执行命名函数,或者它是否完全被变量声明所掩盖?
Function declaration will not be executed there.函数声明不会在那里执行。 Because of the same name usage the function expression overrides the function declaration .由于使用相同的名称,函数表达式会覆盖函数声明。
Is it the standard behavior in Javascript that variables take precedence over functions with the same name?变量优先于同名函数是 Javascript 中的标准行为吗?
Is not about preferring one over other.不是更喜欢一个。 In JavaScript, function declarations are hoisted to the top of the enclosing function or global scope.在 JavaScript 中,函数声明被提升到封闭函数或全局作用域的顶部。 Function expression of same variable name overrides the function declaration.相同变量名的函数表达式会覆盖函数声明。
Example:例子:
foo(); // Function Declaration - will be hoisted
foo = function() { console.log("Function Expression - will NOT be hoisted"); };
function foo() { console.log("Function Declaration - Will be hoisted"); }
foo(); // Function Expression - will NOT be hoisted
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.