You need to add a complete function map! I am still a beginner, this article is all I know about the function, if there is any imperfect or wrong, I hope to point out in the comments, ha ha ha, god do not Sprite.


To view the original image

Functions are objects of the first type in JavaScript (functions are objects), and we can treat functions as JavaScript objects of any type;

  1. Functions can have attributes

Function. The prototype or Function. The arguments...

  1. Functions can have methods

Function.prototype.apply() , Function.prototype.call()Function.prototype.bind()...

  1. Functions can assign values to variables, arrays, or other object attributes to variables
var large=function (){}
var obj={
  large:function(){}
}
Copy the code
  1. Functions can still be called
function large(){},large();
Copy the code
  1. Of course functions also have the same properties as ordinary objects becauseFunctioninheritanceObject
  1. Functions can be passed as arguments to functions (function names are themselves variables, so functions can also be used as values; You can either pass a function as an argument to another function or return a function as the result of another function;)
function add(a,b){
    return a+b
}
function sum(fn,c){
    returnFn + c} sum (add (2, 3), 4); / / 9Copy the code
  1. A function can be returned as a return value
function add(a,b){
    returna+b; } the add (2, 3) / / 5Copy the code

So functions are first type objects, and functions are the main modular unit of code execution

A function is a set of statements that specify the behavior of an object. It is the basic modular unit of JavaScript and is used for code reuse, information hiding, and composite calls.

Programming is the skill of decomposing a set of requirements into a set of functions and data structures

A function name is a pointer to a function object. If there is no function name, we call it an anonymous function. An anonymous function has no pointer to the function object. Normally, we execute the function immediately or assign an anonymous function to a variable.

Two ways to create functions: function declarations and function expressions (anonymous functions, Lamda functions)

Where num1 and num2 are parameters to a function, (parameters, formal arguments) when num1 and num2 are passed as concrete data to a function, they are arguments, (arguments, actual arguments) parameters and arguments

If the number of parameters is greater than the number of arguments, the remaining parameters without corresponding parameters are assigned undefined

If the number of parameters is less than the number of arguments, extra arguments are automatically ignored

The difference between function declarations and function expressions:

We can treat an expression as an anonymous function and assign it to a variable

  1. The parser reads the function declaration first and can access it before executing any code; Function expressions are not actually parsed until the parser executes the code it has created (function declarations are preceded; Function expressions don’t);
  2. Function declarations cannot be followed by parentheses; Expressions can (parentheses after expressions indicate function calls);
  3. Function declarations can only create local functions; Function expressions create global functions

In the body of a function, the scope of a variable declaration begins where it is declared and ends at the end of the function, regardless of code nesting; (that is, the function scope and all variables are destroyed immediately after the function is executed.)

The scope of a named function is the entire scope of the function declared, regardless of code nesting

The inner function can access variables inside outer, forming a closure, which we’ll learn more about later

Function calls pass two implicit arguments: this and arguments;

  1. Arguments Is passed to a function as a collection of all arguments, a class array structure

  2. The context in which this is called depends on where it is called, not when it is declared. There are two special anonymous functions and the timer this points to the window

Anonymous functions

Functions without names are called anonymous functions, all function expressions are anonymous functions, and so are functions called immediately

(function(c){
    returnconsole.log(c); }) (10)Copy the code

JavaScript has no block-level scope, and we often use anonymous functions to mimic block-level scope;

for(var i=0; i<10; i++){ (function(j){
        console.log(j)
    })(i)
}
Copy the code

Anonymous functions are often used in real projects

Recursive function

The function calls itself (references itself) and has termination conditions

  1. Normal named functions recurse
function num(n){
    returnnum>1? (num-1)*num:1; }Copy the code
  1. Recursion in a method
var ninja={
    chirp:function(n){
        returnn>1? ninja.chirp(n-1)*n:1 } }Copy the code

Another problem arises when we recursively use anonymous functions in a method: reference loss;

  var ninja={
    chirp:function(n){
      returnn>1? ninja.chirp(n-1)*n:1; } } var sarural={chirp:ninja.chirp}; var ninja={}; console.log(sarural.chirp(4)); / / an errorCopy the code

The reasons for the error are as follows:So how to solve it?

  var ninja1={
    chirp:function signal(n){
      returnn>1? signal(n-1)*n:1; } } var sarural1={chirp:ninja1.chirp}; console.log(sarural1.chirp(4)); var ninja1={}; console.log(sarural1.chirp(4)); / / 24Copy the code

We can solve the problem by not applying anonymous functions inside functions.Each function object is also created with a Prototype property whose value has a constructor property and whose value is the object of that function

The callback function

Callbacks: A callback is a function that is defined first and executed later, whether in the browser or elsewhere. A callback is a function called within another function

Have you noticed that callbacks are everywhere we write code? Callbacks have become an integral part of JavaScript and are widely used as event handlers

function add(a,b){
    return a+b
}
function sum(fn,c){
    returnFn + c} sum (add (2, 3), 4); / / 9Copy the code

We first defined an add function and then called it in sum. This example is not practical, but it illustrates the concept of a callback function

Recursive function

A function that directly or indirectly calls itself; He decomposed a problem into a set of similar sub-problems, each solved by a common solution; (calling herself to solve her subproblems);

Recursive functions can operate on tree structures very efficiently;

closure

In a nutshell, a closure is a function that can access variables other than the function.

Closures remember a reference to a variable, not its value at the time the closure was created

  1. A simpler closure, if you look at it and see if we use it a lot
<script>
    var num=1;
    function outerFunction() {return num;
    }
    outerFunction()
</script>
Copy the code
  1. Complex closure, one function creates another function
<script>
    var outerValue='ninja';
    var later;
    function outerFunction(){
        var innerValue='samurai';
        function innerFunction(){
            console.log(innerValue);
            console.log(outerValue);
        }
        later=innerFunction;
    }
    outerFunction()
    later();
</script>
Copy the code

After the outerFunction outerFunction is executed, the innerFunction reference is copied to the global reference later. Because the innerFunction reference is copied to the global variable later, the innerFunction exists forever, forming a closure.

Calling later directly returns an error because the innerFunction reference has not been copied to the global variable later

As long as the innerFunction is present, the closure forms the innerValue and outerValue referenced by the function. The function’s innerValue and outerValue are present as long as the function’s innerFunction is present, and the function’s innerValue and outerValue are not reclaimed by javaScript’s recycling mechanism. The closure acts as a protective shield against external access. Nor can it be collected by a recycling mechanism

Problem: Closures hold the entire variable object, not a particular variable; Because closures have to maintain additional scopes, they can take up more memory than other functions and have a performance impact, so use closures with caution.

Private variables: Any variable defined in a function can be considered private. Since these variables are not accessible from outside the function, private variables include parameters to the function, local variables, and other functions defined inside the function

function Private(){
  var num=1;
  this.getnum=function() {return num;
  };
  this.setnum=function(){ num++; console.log(num); } } var private=new Private(); console.log(private.num); Console. log(private.getnum()); Console.log (private.setnum()); console.log(private.setnum());Copy the code

Privileged methods: public methods that have access to private variables and functions; With private and privileged members, you can hide data that should not be directly modified

The method of the Function

Primary functions: String (), Number (), Boolean (), Array (), Object (), Function (), the RegExp (), the Date (), Error (), Symbol (); Primitive functions can be used as constructors directly; The constructor creates a wrapper object that encapsulates the value of the primitive type

  • Function.prototype.apply(): a method that applies one object in the context of another; Arguments can be passed in as arrays.
  • Function.prototype.bind(): The bind() method creates a new Function called the bind Function. When called, the binding function calls the original function with the first argument passed to bind() when it was created as this, and the second and subsequent arguments passed to bind(), plus arguments from the time the binding function itself was run, in that order.
  • Function.prototype.call() : a method that applies an object in the context of another object; Parameters can be passed in as a list.

This points to when the function is called

There are four types of JavaScript calls: normal function calls, method calls, constructor calls, and bind calls

  1. Ordinary function calls
function add(num1,num2){
    console.log(this)
   returnNum1 + num2; } the add (2, 4);Copy the code

If non-strict mode is used, this defaults to pointing to a global object (window); In strict mode, you cannot use a global object for the default binding, so this is bound to undefined;

Method invocation When a function is saved as a property of an object, we call it a method, and this is bound to that object (there are also unexpected cases; Sometimes this will drop the object, and the callback will modify this.

  var ninja={
   chirp:function(n){
     returnn>1? this.chirp(n-1)*n:1; } } var sarural={chirp:ninja.chirp}; console.log(sarural.chirp(4));Copy the code

Constructor call

function Ninja(a){
    this.a=a;
}
var ninja=new Ninja('a');
ninja.a;
Copy the code
  1. Create (construct) a brand new object

  2. This new object is linked by the implementation of [[Prototype]]

  3. This new object is bound to the function call’s this

  4. If the function returns no other object, the function in the new expression automatically returns the new object

Apply (),call(),bind() call patterns apply(),call(),bind() directly binds this to a fixed value

var tim = { 
   name: 'tim', 
   age: 20, 
   getName: function() {
       console.log(this.name);
       return this.name; 
   }
}

var jake = { name: 'jake', age: 20 } tim.getName(); // Tim // Jake objects do not have a getName method, but you can use call/apply to use Tim object getName method tim.getName.call(jake); // jake tim.getName.apply(jake); // jakeCopy the code

Call /apply/bind

A return statement can be used to make a function return prematurely. When a return is executed, the function returns immediately without executing the rest of the statement.

The original link, recently opened a personal wechat public account: Sunseekers. If you are interested, you can follow them