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.
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;
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)
// 块级作用域(通常称为私有作用域)的匿名函数的语法 (function(){ // 块级作用域 })();
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); })();
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());
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"));
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());
setTimeout
function func(param) { return function() { console.log(param); } } var myFunc = func('wheeler'); setTimeout(myFunc, 1000);
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!