Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - 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.

  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?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...