本文介绍了函数和变量具有相同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段是一个测试,用于查看函数和变量在同一范围内共享同一名称时会发生什么。在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.


  1. 命令函数可以被执行,还是被变量声明完全遮盖了?

  2. 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' };

这是关于这个主题的一些好读物:

This is some good read about this topic: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

这篇关于函数和变量具有相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:22