Home > Web Front-end > JS Tutorial > body text

What is the definition of closure in js? Application scenarios of js closure

不言
Release: 2018-09-10 17:29:05
Original
2876 people have browsed it

What this article brings to you is what is the definition of closure in js? The application scenarios of js closure have certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is a closure

A closure refers to a function that has access to a variable in the scope of another function.

function createFunc() {
    var name = "wheeler";
    return function () {
        return name;
    }
}

var nameFunc = createFunc();  // nameFunc是一个闭包

var name = nameFunc();

console.log(name);

// 解除对匿名函数的应用(以便释放内存)
nameFunc=null;
Copy after login

The internal function can access the variable name of the external function. The scope of the internal function includes the scope of the external function.
(Since the closure will carry the scope of the function that contains it, it may occupy memory. Too much, so use closures with caution)

You can reduce excessive memory usage caused by closures by imitating block-level scope

// 块级作用域(通常称为私有作用域)的匿名函数的语法
(function(){
    // 块级作用域
})();
Copy after login

Define closures in block-level scope

// 可以减少闭包占用的内存问题,因为没有指向匿名函数的引用。只要函数执行毕,就可以立即销毁其作用域链了
(function(){
    function createFunc() {
        var name = "wheeler";
        return function () {
            return name;
        }
    }

    var nameFunc = createFunc();

    var name = nameFunc();

    console.log(name);
})();
Copy after login

Application scenarios of closures

  • Use closures to simulate private methods

var returnNum = (function () {
    var num = 0;

    function changeNum(value) {
        num = value;
    }

    return {
        add: function () {
            changeNum(10);
        },
        delete: function () {
            changeNum(-10);
        },
        getNum: function () {
            return num;
        }
    }
})();

// 闭包
console.log(returnNum.getNum());
returnNum.add();
console.log(returnNum.getNum());
returnNum.delete();
console.log(returnNum.getNum());
Copy after login
  • Cache

var CacheCount = (function () {
    var cache = {};
    return {
        getCache: function (key) {
            if (key in cache) {// 如果结果在缓存中
                return cache[key];// 直接返回缓存中的对象
            }
            var newValue = getNewValue(key); // 外部方法,获取缓存
            cache[key] = newValue;// 更新缓存
            return newValue;
        }
    };
})();

console.log(CacheCount.getCache("key1"));
Copy after login
  • Encapsulation

var person = function(){
    var name = "default";//变量作用域为函数内部,外部无法访问
    return {
        getName : function(){
            return name;
        },
        setName : function(newName){
            name = newName;
        }
    }
}();

console.log(person.name);// undefined
console.log(person.getName());
person.setName("wheeler");
console.log(person.getName());
Copy after login
  • setTimeout

function func(param) {
    return function() {
        console.log(param);
    }
}
var myFunc = func('wheeler');
setTimeout(myFunc, 1000);
Copy after login
  • Protect variables within functions.

  • Maintain a variable in memory.

Related recommendations:

What is js closure? Understanding js closure (with code)

What is js closure? Understanding js closure

The above is the detailed content of What is the definition of closure in js? Application scenarios of js closure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template