Three definition methods of JS function

  • 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(){
    • 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(){

    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;
      //Define functions through constructor methods
      var fn = new Function('var a = "1";console.log(a)');
      //Add parameter
      var fn2 = new Function('a','b','var a = "1";console.log(a+b)');

      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