Advanced usage of front-end closures

What is a closure?

The meaning of closure is actually to define another function (function nested function) inside a function and return this internal function. In this way, the inner function forms a closure and can access the variables and parameters of the outer function.

function outFunction(){
    let outValue = "这是一个闭包";
    function innerFunction(){
        console.log(outValue);
    }
    return innerFunction;
}

const closure = outFunction();
closure();     // 输出 "这是一个闭包"

In front-end development, there are five main functions:

protected variables

Closures can be used to protect variables so that they cannot be directly accessed or modified from the outside. With closures, we can create private variables that can only be accessed and modified by inner functions.

function creatCounter(){
    let count = 0;
    return {
        increment: function(){
            count++;
        },
        decrement: function(){
            count--;
        },
        getCount: function(){
            return count;
        }
    }
}

const counter = creatCounter();
console.log(counter.getCount());    // 0

counter.increment();
counter.increment();
console.log(counter.getCount());    // 2

counter.decrement();
console.log(counter.getCount());    // 1

Data encapsulation

Closures can be used for data encapsulation to encapsulate and access data by creating private variables and public methods.

function createPerson(name,age){
    let _name = name;
    let _age = age;
    return {
        getName: function(){
            return _name;
        },
        getAge: function(){
            return _age;
        },
        setName: function(newValue){
            _name = newValue;
        },
        setAge: function(newValue){
            _age = newValue;
        }
    }
}

const person = createPerson("张三",18);

console.log(person.getName());  // 张三
console.log(person.getAge());   // 18

person.setName("李四");
person.setAge(20);

console.log(person.getName());  // 李四
console.log(person.getAge());   // 20

memory effect

Closures can be used to implement memoization functions, which can cache and reuse previous calculation results during function execution to improve function execution efficiency.

function memoize(func){
    let cache = {};
    return function(){
        if(n in cache){
            return cache[n];
        }
        const result = func(n);
        cache[n] = result;
        return result
    }
}

// 计算平方
function square(n){
    return n*n
}
// 使用记忆优化平方函数
const memoizeSquare = memoize(square);

console.log(memoizeSquare(2));  // 4
console.log(memoizeSquare(2));  // 4  直接从缓存中获取结果 结果为16

function factory

Closures can implement function factories, which are functions that create and return other functions. We can use function factory to generate functions with similar functions based on different configuration parameters, making the code more flexible and reusable.

function createMultiply(multiplier){
    return function(number){
        return number * multiplier;
    }
}

// 创建函数工厂
const double = createMultiply(2);
const triple = createMultiply(3);

console.log(double(3)); // 6
console.log(triple(3)); // 9

Asynchronous operations

Closures can be used to implement asynchronous operations. By using closures, we can capture and retain state during asynchronous operations.

function asyncFunction(callback){
    setTimeout(function(){
        const result = "Hello world";
        callback(result);
    },2000)
}

asyncFunction(function(result){
    console.log(result);
});

おすすめ

転載: blog.csdn.net/a_strong_pig/article/details/135132905