closure
Closures can be interpreted as telling the browser that these variables are still available and can’t be garbage collected.
Why do YOU need closures
Let’s not recite the eight-part essay, look at the following code
function foo(){
var a = 1;
console.log(a); / / 1
}
console.log(a); / / an error
Copy the code
The final print will report an error that we cannot use a in foo. Because the scope is different, what if we want to access a in foo?
What is a closure
function foo(){
var a = 1;
return a;
};
const a = foo();
console.log(a); / / 1
Copy the code
So we can access a in foo.
Browsers have limited memory, so local variables within functions are created during the execution of the function and destroyed upon completion. If you don’t want it destroyed, keep references to local variables in external variables. Example: the global a in the code above preserves a reference to a in foo, and a in foo is not destroyed.
Powerful closures
Encapsulated module
When writing a project, if all variables are defined in the global scope, it can cause problems such as excessive memory consumption and variable names that are easy to duplicate. Closures allow us to divide projects into chunks, with each function having its own scope. This makes code planning clearer and more reusable.
Look at this example: made a class information module, exposed add,del,getInfo, can add students, reduce students,get student information.
- Info Stores all information.
- Add Adds data to info.
- Del Deletes the corresponding data in info.
- GetInfo gets information about the class.
const classInfo = (function() {
let info = [];
function add(name, age) {
info.push({
name,
age,
})
}
function del(name) {
info = info.filter(i= >i.name ! == name)return info;
}
function getInfo() {
return info;
}
return {
add,
del,
getInfo
}
})()
console.log(classInfo.getInfo()) / / []
classInfo.add('xiaohong'.18)
classInfo.add('xiaoming'.28)
classInfo.add('xiaowang'.38)
console.log(classInfo.getInfo()) / / / {}, {}, {}
classInfo.del('xiaowang')
console.log(classInfo.getInfo()) / / / {}, {}
Copy the code
Modularity practices
Modularity refers to collaboration between modules. Let’s declare a few modules:
Store the name module
const allName = function (){
const names = [];
function add(name) {
names.push(name);
}
function getNames() {
return names;
}
return {
add,
getNames
}
}
Copy the code
Storage Age module
const allAge = function (){
const ages = [];
function add(age) {
ages.push(age);
}
function getAges() {
return ages;
}
return {
add,
getAges
}
}
Copy the code
A module that integrates name and age information
const getNameAge = function(names, ages) {
function getNameAge() {
const nameArr = names.getNames();
const ageArr = ages.getAges();
const data = [];
for (let i = 0; i < nameArr.length; i++) {
data.push({
name: nameArr[i],
age: ageArr[i],
});
}
return data;
}
return {
getNameAge
}
};
Copy the code
The module combination
- Module. define Register module, register time. If other modules are used, they are passed in as arguments.
- Module. get Gets the module.
const module = (function () {
const modules = {};
function define(key, dep, impo) {
const args = [];
for (let key of dep) {
if (modules[key]) {
args.push(modules[key])
}
}
modules[key] = impo.apply(null, args)
}
function get(key) {
return modules[key];
}
return {
define,
get
}
})()
Copy the code
Register and obtain
module.define('names', [], allName);
module.define('ages', [], allAge);
module.define('getNameAge'['names'.'ages'], getNameAge);
const impoName = module.get('names');
const impoAge = module.get('ages');
const impoGetNameAge = module.get('getNameAge');
Copy the code
The verification results
Add data, print it, and see if it’s correct. This enables the joint use of multiple modules.
impoName.add('xiaoma');
impoAge.add(18);
impoName.add('xiaowang');
impoAge.add(20);
impoName.add('xiaoli');
impoAge.add(22);
console.log(impoGetNameAge.getNameAge())
Copy the code
conclusion
Modularity is very important for development, and closure is the key technology to achieve modularity. As a beginner js must have a deep understanding of it.