简体   繁体   中英

What is the order of execution of declarations in JavaScript?

<script type="text/javascript">
        function func(){
        }
        var foo="foo";
</script>

<script type="text/javascript">
        var foo="foo";
        function func(){
        }
</script>

At the beginning, when func is a function and foo is "undefined", but I want to know which is the first to be defined, func or foo?

Identifiers of both, variable and function declarations (and also formal parameters for function code ) are made when entering the execution context , that's actually before the code execution.

In the case of variables, as you noted it, they are initialized with the undefined value at that stage, the assignment takes places after, when control reaches the assignment expression, eg:

var foo = "outer";
(function () {
  alert(foo); // undefined
  var foo = "inner";
})();

In the above code, we can see how the foo identifier holds the undefined value, that's because when entering the function execution context, the local foo variable was initialized.

That's one of the reasons why people recommend to declare your variables at the top of the function (to resemble what actually happens)

Functions declarations are also hoisted , you can actually use them before its declaration, because as we know, it was made before the code execution, for example:

func(); // "bar"
function func () {
  return "bar";
}

See also:

In

var foo = "foo";
function func() {
}

there are two things going on

  1. Declaration
  2. Initialization

foo and func are declared simoultaneously.

The initialization of func is hoisted to the top. So functions are initialized before var s.

So the order of operations is

  1. foo and func declared
  2. func initialized to a Function object
  3. foo initialized to "foo"

This is clearest in the code

var foo = bar;
function bar() {}

where after this code runs, typeof foo === 'function' .

我相信标识符会在遇到声明时被定义。

Functions in javascript are always parsed and defined first.

<script type="text/javascript">
    alert('before func: ' + func);        // Print function as string
    alert('before somevar: ' + somevar);  // Print undefined

    function func() {
    }

    var somevar = "hello";

    alert('after func: ' + func);         // Print function as string
    alert('after somevar: ' + somevar);   // Print hello
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM