use*_*829 6 javascript closures
高阶函数定义为:
将函数作为参数和/或返回函数作为返回值的函数。
关闭示例:
function outer() {
const name = 'bob';
function inner(lastName) {
console.log('bob' + lastName);
}
return inner;
}
Run Code Online (Sandbox Code Playgroud)
上面定义的闭包是否属于这一类?看起来他们返回一个函数作为返回值,对吗?
闭包并不会意味着它一定是由函数返回。在 JavaScript 中,每个函数实际上都是一个闭包。闭包通常是一个可以访问声明上下文范围的函数。
function outer(lastName)
{
const name = 'Bob';
function inner(lastName)
{
// here we have access to the outer function's scope
// thus it IS a closure regardless whether we return the function or not
console.log(name + ' ' + lastName);
}
inner(lastName);
}
outer('Marley');Run Code Online (Sandbox Code Playgroud)
更具体地说:闭包实际上是将当前作用域绑定到子上下文的概念。我们经常简短地对获得这种映射上下文的函数说“闭包”。声明上下文并不意味着声明时间,而是在其调用时处于活动状态的声明上下文。此行为用于将上下文绑定到内部函数并返回具有绑定上下文的函数:
function outer(lastName)
{
// this is the declaration context of inner().
const name = 'Bob';
function inner()
{
// here we have access to the outer function's scope at its CALL time (of outer)
// this includes the constand as well as the argument
console.log(name + ' ' + lastName);
}
return inner;
}
var inner1 = outer('Marley');
var inner2 = outer('Miller');
function output()
{
// this is the caller context, the const name ist NOT used
const name = 'Antony';
inner1(); // outputs 'Bob Marley'
inner2(); // outputs 'Bob Miller'
}
// test the output
output();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2191 次 |
| 最近记录: |