What is a closure

A function declared inside a function that can access local variables of the function

/ / method
let p2=(function(){
	let num=100
    return function(){
    	return num
    }
}())
p2()
Copy the code

The role of closures

Promote the variable life cycle

The life cycle of a variable: from its declaration to its collection. Global variables: the js code from the start of execution to the end of execution promotes the life cycle of a variable that was intended to be recycled, but was not recycled

function fn(){
	let num=10
    function add(){
    	console.log(num)
    }
    function rem(str){
    	let str1=str>0? str:0
    }
    return{
    	getNum:add,
        setNum:rem
    }
}
let p1=fn()// Return an object containing two methods
p1.getNum()
Copy the code

Declare a private property

// Closures can declare private attributes
// write the constructor
function Student(name,age){
	this.name=name
    this.age=age
}
// Instantiate the student object: properties such as name and age can be accessed directly from the object
let s1=new Student('jack'.20)
console.log(s1.name)
console.log(s1.age)

// Declare a constructor for a private property
function Student(name){
	let age=20
    this.name=name
    // How to operate on age
    this.setAge=function(value){
    	if(value>=0&&value<=100){
			age=value
    }
    this.getAge=function(){
    	return 'My age cannot be disclosed.... '}}// Instantiate a student object: the student object cannot access age and must use the setAge() and getAge() methods
let s2=new Student('luck')
console.log(s2.name) //luck
console.log(s2.setAge())/ / 20
Copy the code

Note the use of closures

// If you want local variables inside a function to be the same every time you use them, then external functions can only be called once
function outer(){
	let num=Math.floor(Math.random()*100)
    function inner(){
    	console.log(num)
    }
    return inner
}
let fn=outer()
fn()
fn()

outer()()
outer()()
Copy the code