-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosure.js
44 lines (35 loc) · 983 Bytes
/
closure.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function f1() {
var a = 100;
/*return function f2(){
console.log(a);
}*/
function f2() {
console.log(a);
}
return f2;
}
f1()();
//? Closures :
//? Closure is an important JavaScript pattern to give private access to a variable
function closures(val) {
return function (name) {
console.log(val + " " + name);
};
}
const greet = closures("Hello");
greet("Kirtti");
//* In a more real-world scenario, you could envision an initial function apiConnect(apiKey) that returns some methods that would use the API key. In this case, the apiKey would just need to be provided once and never again.
function apiConnect(apiKey) {
function get(route) {
return fetch(`${route}?key=${apiKey}`);
}
function post(route, params) {
return fetch(route, {
method: "POST",
body: JSON.stringify(params),
headers: { Authorization: `Bearer ${apiKey}` },
});
}
return { get, post };
}
const api = apiConnect("my-secret-key");