Why can I use a function before it's defined in JavaScript?

前端 未结 7 1814
日久生厌
日久生厌 2020-11-22 16:07

This code always works, even in different browsers:

function fooCheck() {
  alert(internalFoo()); // We are using internalFoo() here...

  return internalFoo         


        
7条回答
  •  不要未来只要你来
    2020-11-22 16:48

    It is called HOISTING - Invoking (calling) a function before it has been defined.

    Two different types of function that I want to write about are:

    Expression Functions & Declaration Functions

    1. Expression Functions:

      Function expressions can be stored in a variable so they do not need function names. They will also be named as an anonymous function (a function without a name).

      To invoke (call) these functions they always need a variable name. This kind of function won't work if it is called before it has been defined which means Hoisting is not happening here. We must always define the expression function first and then invoke it.

      let lastName = function (family) {
       console.log("My last name is " + family);
      };
      let x = lastName("Lopez");
      

      This is how you can write it in ECMAScript 6:

      lastName = (family) => console.log("My last name is " + family);
      
      x = lastName("Lopez");
      
    2. Declaration Functions:

      Functions declared with the following syntax are not executed immediately. They are "saved for later use" and will be executed later, when they are invoked (called upon). This type of function works if you call it BEFORE or AFTER where is has been defined. If you call a declaration function before it has been defined Hoisting works properly.

      function Name(name) {
        console.log("My cat's name is " + name);
      }
      Name("Chloe");
      

      Hoisting example:

      Name("Chloe");
      function Name(name) {
         console.log("My cat's name is " + name);
      }
      

提交回复
热议问题