Closure
Important javascript pattern to give private access to a variable. In this example, createGreeter
returns an anonymous function that has access to the supplied greeting, "Hello." For all future uses, sayHello
will have access to this greeting!
function createGreeter(greeting) {
return function(name) {
console.log(greeting + ', ' + name);
};
}
const sayHello = createGreeter('Hello');
sayHello('Joe');
// Hello, Joe
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');
// No need to include the apiKey anymore
api.get('http://www.example.com/get-endpoint');
api.post('http://www.example.com/post-endpoint', { name: 'Joe' });