mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-22 19:46:23 +00:00
35 lines
756 B
Markdown
35 lines
756 B
Markdown
|
---
|
||
|
id: 8659a753-2c0d-46cb-afdc-095e318aabff
|
||
|
title: Closure in JavaScript
|
||
|
---
|
||
|
|
||
|
Local bindings are created anew for every call, and different calls
|
||
|
can't affect on another calls local bindings.
|
||
|
|
||
|
``` javascript
|
||
|
function wrapValue(n) {
|
||
|
let local = n;
|
||
|
return () => local;
|
||
|
}
|
||
|
|
||
|
let wrap1 = wrapValue(1);
|
||
|
let wrap2 = wrapValue(2);
|
||
|
console.log(wrap1());
|
||
|
console.log(wrap2());
|
||
|
```
|
||
|
|
||
|
A function that references bindings from local scopes around it is
|
||
|
called a closure. This behavior not only frees you from having to worry
|
||
|
about lifetimes of bindings but also makes it possible to use function
|
||
|
values in some creative ways.
|
||
|
|
||
|
``` javascript
|
||
|
function multiplier(factor) {
|
||
|
return number => number * factor;
|
||
|
}
|
||
|
|
||
|
let twice = multiplier(2);
|
||
|
|
||
|
console.log(twice(5));
|
||
|
```
|