This article brings you to the content is about JS in the definition of closure is what? JS closure of the application scenario, there is a certain reference value, there is a need for friends to refer to, I hope you have some help.
What is a closure package
Closures are functions that have access to variables in another function scope.
function Createfunc () { var name = "Wheeler"; return function () { return name; }} var namefunc = Createfunc (); Namefunc is a closed-packet var name = Namefunc (); Console.log (name);//de-Application of anonymous functions (in order to free memory) Namefunc=null;
The intrinsic function can access the variable name of the external function, and the scope of the inner function contains the scope of the outer function
(Because the closure carries the scope of the function that contains it, it can result in too much memory, so use closures sparingly)
You can reduce the memory consumption caused by closures by mimicking block-level scopes
Syntax for anonymous functions (function () { //block-level scope}) for block-level scopes (often referred to as private scopes);
Defining closures in block-level scopes
You can reduce the memory problems that are used by closures because there are no references to anonymous functions. As long as the function executes, it can immediately destroy its scope chain (function () { function Createfunc () { var name = "Wheeler"; return function () { return name; } } var namefunc = Createfunc (); var name = Namefunc (); Console.log (name);}) ();
Closure application Scenarios
var Returnnum = (function () { var num = 0; function Changenum (value) { num = value; } return { add:function () { changenum (Ten) }, delete:function () { changenum ( -10); },< C21/>getnum:function () { return num;}} }) ();//Closures Console.log (Returnnum.getnum ()); Returnnum.add (); Console.log (Returnnum.getnum ()); Returnnum.delete (); Console.log (Returnnum.getnum ());
var Cachecount = (function () { var cache = {}; return { getcache:function (key) { if (key in cache) {//If the result is returned in the cache cache[key];//directly returns the object in the cache } var newvalue = Getnewvalue (key); External method, get cache Cache[key] = newvalue;//Update cache return newvalue;}} ) (); Console.log (Cachecount.getcache ("Key1"));
var person = function () { var name = ' default ';//variable scope is inside function, external cannot access return { getname:function () { return name; }, setname:function (newName) { name = NewName;}} } (); Console.log (person.name);//Undefinedconsole.log (Person.getname ());p erson.setname ("Wheeler"); Console.log ( Person.getname ());
function func (param) { return function () { console.log (param);} } var MyFunc = func (' Wheeler '); SetTimeout (MyFunc, 1000);