闭包是一个重要的JavaScript模式,可以私有访问变量。在本例中,createGreeter返回一个匿名函数,这个函数可以访问参数 greeting(在这里是“Hello”)。在后续的调用中,sayHello 将有权访问这个 greeting!
function createGreeter(greeting) {
return function(name) {
console.log(greeting + ', ' + name);
}
}
const sayHello = createGreeter('Hello');
sayHello('Joe');
// Hello, Joe在更真实的场景中,你可以设想一个初始函数apiConnect(apiKey),它返回一些使用API key的方法。在这种情况下,apiKey 只需要提供一次即可。
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' }); 






网友评论文明上网理性发言 已有0人参与
发表评论: