javascript 同名的函数和变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15057649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:19:31  来源:igfitidea点击:

Function and variable with the same name

javascriptsyntax

提问by Mark Fox

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 中,变量定义似乎具有优先权。

  1. Can the named function be executed, or is it completely obscured by the variable declaration?
  2. Is it the standard behavior in Javascript that variables take precedence over functions with the same name?
  1. 命名函数是否可以执行,或者它是否完全被变量声明所掩盖?
  2. 变量优先于同名函数是 Javascript 中的标准行为吗?

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>

采纳答案by Niko

In JavaScript, function definitions are hoisted to the top of the current scope. Your example code therefore reads as:

在 JavaScript 中,函数定义被提升到当前作用域的顶部。因此,您的示例代码如下:

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