Details of Function type in javascript

  • 2020-06-03 05:47:43
  • OfStack

Function type

The function type, of course, is one of the most important things in js.

1. This thing is first 1 object, which means it is a reference type. Statement: 1 Is said to be an object, is there a very 1 kind of its base class is object object illusion, No,

It's two separate things from object. When you typeof function, you return funciton not object

2. Each function is an instance of an Function object that has properties and methods like other reference objects 1. Since it is an object, the function name is a pointer to the function object

Syntax support for declarations of functions:


<script>

  // way 1
  function fun(num1,num2){
    return num1+num2;
  }
  
  // way 2
  var fun=function(num1,num2){
    return num1+num2;
  };

  // way 3
  var fun=new Function("n1","n2","return n1+n2");
  
</script>

Each of the three approaches completes the declaration of a function, but each differs.

Mode 1 is understood as a declaration of a function, mode 2, and mode 3 as a function expression. (Method 3 is not recommended, the reason will cause the code to be parsed twice, first explain the regular ECMAScript code, in the interpretation of the passed parameters, this kind

The argument can be N, but the last one is treated as the body of the function.

The main reason for the difference is that the js parser resolves function declarations and function expressions differently. The parser reads the function declaration first, and the js engine automatically puts the function declaration at the top of the execution environment when it executes.

Function expressions, on the other hand, are not interpreted until they are executed. It's important to understand this!

Look at the code


<script>
  console.log(typeof fun); //"function"
  console.log(typeof fun2); //"undefined"
  console.log(typeof fun3); //"undefined"
  function fun(n1,n2){
   return n1+n2;
  }
  var fun2=function(n1,n2){
   return n1+n2;
  }
  var fun3=new Function("n1","n2","return n1+n2;");
 </script>

3. Why is the function not overloaded?

Consider the language features of js. As stated in article 2, a function name is simply a pointer to a function object. It's clear from the concept of Pointers.

Look at the code example:


<script>
  function fun(n1){
   return n1+100;
  }
  function fun(n1){
   return n1+200;
  }
  console.log(fun(1));// 201 
  
  // The above writing should be 
  
  var fun=function(n1){
    return n1+100;
  }
  fun=function(n1){
   return n1+200;
  }
  
  // fun  "Is overridden 
  console.log(fun(1));// 201 
 </script>

Today write this, is to write the basic concept, hope to have a blind spot to help! There is any need to correct the place, I hope you bossy comments correct.

This is the end of this article, I hope you enjoy it.


Related articles: