Closures and advanced functions in JavaScript

Keywords: Front-end Javascript Programming Lambda PHP

In JavaScript, functions are first-class citizens. JavaScript is an object-oriented programming language, but it also has many features of functional programming, such as Lambda expressions, closures, high-order functions, etc. functional programming is a programming paradigm.

function dada() {
 var a = 1;
 var b = function() {
  console.log(a);
 }
 return b 
 // b is a closure function, because it can access the scope of dada function
}

JavaScript functions are also objects, which can have attributes, can be assigned to a variable, can be placed in an array as an element, can be used as attributes of other objects, and can do anything else, it can do what other objects can do, and it can do what other objects can't.

Functions are the same as other ordinary objects. There are properties and methods. Ordinary objects can do as well as functions. Learning closures and advanced functions in JavaScript is the basic part!

So what is a closure? A closure is a function that has access to variables and parameters in its external scope.

var func = (function() {
 var item = 0;
 return {
  add: function(num) {
   item += typeof num === 'number' ? num : 1;
  },
  value: function() {
   return item;
  }
 }
})();

The closure function can access variables and parameters in the context in which it was created, except for this and arguments.

Closure:

Function as return value, higher-order function can not only accept function as parameter, but also return function as result value. The formation of closures is closely related to the action of variables and the life cycle of variables.

Variable scope:

var func = function() {
 var a = 1;
 console.log(a); // 1
}
func();
console.log(a); // Uncaught ReferenceError: a is not defined

Closure is a function that can access internal variables of other functions. The focus of closure is the scope of variables, and the life cycle of variables.

Scope of variable

// Scope of variable
var my = function() {
 var a = 1;
 console.log('my', a); // 1
}
my();
console.log(a) // ReferenceError: a is not defined

Declaration period of variable

// Life cycle of variable
let fu = function() {
 let a = 0;
 a++;
 console.log('dada', a);
}
fu(); // 1
fu(); // 1
fu(); // 1

let func = function() {
 let a = 0;
 return function() {
  a++;
  console.log('a', a);
 }
}

let fun = func()

fun(); // 1
fun(); // 2
fun(); // 3

The variables in the closure are not destroyed, which involves the garbage collection mechanism, i.e. clear marking and reference counting

function num() {
 for(var i=0; i< 10; i++) {
  setTimeout(function() {
   console.log('da', i) // 10
  },0)
 }
}
num();

function num1() {
 for(var i=0; i< 10; i++) {
  (function (i) {
   setTimeout(function() {
    console.log('da', i)
   },0)
  })(i) // 1,2,3,...,10
 }
}
num1()

An example of what a closure is:

function da() {
 var a = 1;
 function dada() {
  console.log(a);
 }
 return dada
}

var d = da();
d(); // 1

If closures are not that necessary, do not create them because closures have a negative impact on performance in terms of processing speed and memory consumption.

The form of closure is closely related to the scope of variable and the life cycle of variable.

Scope of variable:

The scope of variable refers to the effective range of variable. When a variable declared in a function does not have the keyword var, the variable becomes a global variable. When the variable is declared with var, the variable becomes a local variable, which can only be accessed inside the function, but not outside the function. Give an example:

var func = function() {
 var a = 1;
 alert(a); // 1
};
func();
alert(a); // Uncaught ReferenceError: a is not defined

Nesting example:

var a = 1;
var fun = function() {
 var b = 2;
 var func1 = function() {
  var c = 3;
  alert(b); // 2
  alert(a); // 1
 }
 func1();
 alert(c); // c is not defined
};
fun();

Life cycle of variable:

Another important concept of closures, the life cycle of variables, is permanent for the life cycle of global variables, and short for the local variables inside functions. They will be destroyed with the end of the call.

var func = function() {
 var a = 1;
};
func();
var func = function() {
 var a = 1;
 return function() {
  a++;
  alert(a);
 }
};
var da = func();
da(); // 2
da(); // 3
da(); // 4

closure

Function as return value

function num(arr) {
 return arr.reduce(function (x,y) {
  return x + y;
 });
}
num([1,2,3]); // 6

Turn function

function func(arr) {
 var sum = function() {
  return arr.reduce(function(x,y) {
   return x + y;
  });
 }
 return sum;
}

// Call function
var da = func([1,2,3]); // Calling function

// Function
da(); // 6

var da1 = func([1,2]);
var da2 = func([1,2]);
da1 == da2 // false

Each call returns a new function

Caching with closures:

function add(a) {
 return a + 1;
}

Caching with closures:

The function of closure

Encapsulate variables. Closures can encapsulate private variables:

var da = function() {
 var a = 1;
 for (var i=0; i < arguments.length; i++){
  a = a * arguments[i];
 }
 return a;
}
alert(a(1,2,3));

There is no concept of block level scope in JavaScript:

function add() {
 var arr = [ 1,2,3 ];
 for (var i=0; i < arr.length; i++) {
  alert( arr[i]);
 }
 var i; // Redeclare variables
 alert(i);
}

Block level scope effect, closure:

(function() {
 // Block level scope
})()

Continue the life cycle of local variables:

var myImg = function( src ) {
 var img = new Image(0;
 img.src = src;
};
myImg('http:///...');

Resolve request loss:

var da = (function() {
 var imgs = [];
 return function(src) {
  var img = new Image();
  imgs.push(img);
  img.src = src;
 }
})();

A closure is a function that has access to variables in the scope of another function.

Closure: function objects can be associated through scope, and variables in function body can be saved in function scope.

Lexical scope: the scope is determined when writing code Dynamic scope: the scope is determined when the code is running

<script>
function add(num){
    var sum = 5;
    return sum + num;
}
var sum = add(4);
</script>
Execution Contexts = {
    variable object: Variable object;
    this value: this Pointer;
    scope chain: Scope chain;
}

global variable

function myFunction() {
    var a = 4;
    return a * a;
}
var a = 4;
function myFunction() {
    return a * a;
}
var counter = 0;
 
function add() {
   return counter += 1;
}
 
add();
add();
add();
 
// The counter is now 3
function add() {
    var counter = 0;
    return counter += 1;
}
 
add();
add();
add();
 
// The original intention is to output 3, but it backfires. The output is 1!
function outter(){
  var sky="blue";
  function inner(){
    console.log(sky);
  }
  return inner;
}

var result=outter();
result();    //"blue"

A function and a reference to its state, the lexical environment, form a closure, that is, a closure that allows you to access the scope of an external function from an internal function.

Lexical scope:

function init() {
    var name = "dada"; 
    // name is a local variable created by init
    function displayName() { 
    // displayName() is an intrinsic function, a closure
        alert(name); 
        // Variable declared in parent function used
    }
    displayName();
}
init();

Closure:

function mFunc() {
    var name = "dada";
    function displayName() {
        alert(name);
    }
    return displayName;
}

var myFunc = mFunc();
myFunc();

Higher order function

What is a high-order function? Functions in JavaScript all point to a certain variable. Since variables can point to functions and parameters of functions can receive variables, then one function can receive another function as a parameter, which is called a high-order function.

Advanced functions:

function add(x, y, f) {
    return f(x) + f(y);
}

'use strict';

function pow(x) {
    return x * x;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); 
// [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
var f = function (x) {
    return x * x;
};

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var result = [];
for (var i=0; i<arr.length; i++) {
    result.push(f(arr[i]));
}
var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x + y;
}); 
// 25
var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x * 10 + y;
}); 
// 13579

In an array, delete the even number and keep the odd number:

var arr = [1, 2, 4, 5, 6, 9, 10, 15];
var r = arr.filter(function (x) {
    return x % 2 !== 0;
});
r; 
// [1, 5, 9, 15]

Callback function

var arr = ['A', 'B', 'C'];
var r = arr.filter(function (element, index, self) {
    console.log(element); 
    // Print 'A', 'B', 'C' in sequence
    console.log(index); 
    // Print 0, 1, 2 in turn
    console.log(self); 
    // self is the variable arr
    return true;
});
'use strict';

var arr = [10, 20, 1, 2];
arr.sort(function (x, y) {
    if (x < y) {
        return -1;
    }
    if (x > y) {
        return 1;
    }
    return 0;
});
console.log(arr); 
// [1, 2, 10, 20]
var a1 = ['B', 'A', 'C'];
var a2 = a1.sort();
a1; 
// ['A', 'B', 'C']
a2; 
// ['A', 'B', 'C']

a1 === a2; 
// true, a1 and a2 are the same object

The every() method can determine whether all elements of the array meet the test conditions

The find() method is used to find the first element that meets the criteria

The findIndex() method returns the index of this element

A higher-order function is one in which the input parameter is a function or the output is a function

function add() {
    var num = 0
    return function(a) {
        return num = num + a
    }
}
var adder = add()

adder(1)     
// Output: 1
adder(2)     
// Output: 3

The higher-order function satisfies the condition that the function is passed as a parameter and the function is output as a return value

Callback function:

var getUserInfo = function( userId, callback ){
    $.ajax( 'http://xxx.com/getUserInfo?' + userId, function( data ){
        if ( typeof callback === 'function' ){
            callback( data );
        }
    });
}
getUserInfo( 522624714, function( data ){
    alert ( data.userName );
});
//Arrange from small to large
[ 1, 5, 3 ].sort( function( a, b ){
    return a - b;
});
// Output: [1, 3, 5]

//From large to small
[ 1, 5, 3 ].sort( function( a, b ){
    return b - a;
});
// Output: [5, 3, 1]

What is functional programming? Functional programming is a form of programming that allows you to pass functions as parameters to other functions and return functions as values.

In JavaScript, functions are a special class of objects:

function hello() {
 console.log('hello');
}
hello();
hello.name='da';

console.log(hello.name); // da
const num = function(x) {
 return x*x;
}

num(8); // 64

A higher-order function is a function that receives functions as parameters or returns functions as output values. High order function practice:

const arr1 = [1,2,3];
const arr2 = arr1.map(function(x) {
 return x * 2;
});
console.log(arr2);
const arr1 = [1,2,3];
const arr2 = arr1.map(x => x*2);

epilogue

In short, a higher-order function is a function that can accept a function as a parameter, return a value, and return a function. Closures allow you to access external function scopes from internal functions. A closure is a function that can access variables in the scope of another function.

About the content of the current article that involves the front-end, PHP knowledge points, if you are interested in it, you can pay attention to it. It's a great honor to be found by you. It's really smart to know English! Thank you for your attention. In the future, I hope to support me silently all the time, and I will try to write more excellent works. We grow up together, from zero basic programming, to present the Web front-end field, data structure and algorithm, network principle and other easy to understand to small partners. Share technical articles, tool resources, selected courses and hot information related to Web front-end.

Recommended reading

1. How much do you know about this, new, bind, call, apply? Then I'll tell you

2. Why to learn JavaScript Design pattern, because it is the core

Feedback: If the content of this number is not in place (for example, involving copyright or other issues), please contact us in time for rectification, and we will deal with it as soon as possible.

Thanks for reading. It's not easy to be original. Just like it. It's my biggest motivation for writing.

Welcome to your attention. Dada The short book!

This is a blog with quality and attitude

Posted by Petran76 on Thu, 14 Nov 2019 21:49:39 -0800