Three definition methods of JS function

Time:2021-7-30
  • How functions are defined

    • Function declaration: it must have a name. It will promote the function. It has been created in the pre parsing stage. It can be called before and after the declaration

      //Function declaration
      //Define function name
      function fn(){
           console.log(123);
      }
    • Function expression: a variable assignment function expression can have no name (anonymous function) and no function promotion.

      //Assign a function to a variable, which can be an anonymous function
      var fn = function(){
          console.log(123);
      };

    Because function declaration is promoted, function declaration function can be called before function declaration, and function defined by function expression can not, it carries on a variable assignment, the essence will carry on variable declaration promotion, if written in front, it only fixed a variable, and no assignment, its internal undefined, unable to perform function. Will report an error.

    • new Function

      The function itself is also an object that can call properties and methods

      //Function declaration method
      //With parameters
      function fun(a,b){
          var a = 1;
          console.log(a+b);
      }
      function(2,3);
      
      //Define functions through constructor methods
      var fn = new Function('var a = "1";console.log(a)');
      fn();
      
      //Add parameter
      var fn2 = new Function('a','b','var a = "1";console.log(a+b)');
      fn2(2,4);

      This method is actually equivalent to a pile of strings in the brackets of new function. It is slow to parse, inefficient and error prone.

      console.dir(fn2);// New function () is a function and an object with its own properties and methods

      New function () is a function and an object with its own properties and methods

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tDlXMd1O-1615787758524)(C:\Users\xiaomi\AppData\Roaming\Typora\typora-user-images\image-20210315132052565.png)]