javascript闭包
If you’ve ever written a function in JavaScript, you already made use of closures.
如果您曾经用JavaScript编写过函数 ,那么您已经使用了Closures 。
It’s a key topic to understand, which has implications on the things you can do.
这是一个重要的主题,对您可以做的事情有影响。
When a function is run, it’s executed with the scope that was in place when it was defined, and not with the state that’s in place when it is executed.
运行一个函数时,将使用定义该函数时已存在的作用域来执行该函数 ,而不是使用执行该函数时所处于的状态来执行它。
The scope basically is the set of variables which are visible.
范围基本上是可见的变量集。
A function remembers its Lexical Scope, and it’s able to access variables that were defined in the parent scope.
函数会记住其Lexical Scope ,并且能够访问在父作用域中定义的变量。
In short, a function has an entire baggage of variables it can access.
简而言之,一个函数具有可以访问的全部变量。
Let me immediately give an example to clarify this.
让我立即举一个例子来澄清这一点。
const bark = dog => {
const say = `${dog} barked!`
;(() => console.log(say))()
}
bark(`Roger`)
This logs to the console Roger barked!
, as expected.
这记录到控制台Roger barked!
,正如预期的那样。
What if you want to return the action instead:
如果您想返回该操作怎么办:
const prepareBark = dog => {
const say = `${dog} barked!`
return () => console.log(say)
}
const bark = prepareBark(`Roger`)
bark()
This snippet also logs to the console Roger barked!
.
此代码段也记录到控制台, Roger barked!
。
Let’s make one last example, which reuses prepareBark
for two different dogs:
让我们做最后一个示例,该prepareBark
为两只不同的狗重复使用prepareBark
:
const prepareBark = dog => {
const say = `${dog} barked!`
return () => {
console.log(say)
}
}
const rogerBark = prepareBark(`Roger`)
const sydBark = prepareBark(`Syd`)
rogerBark()
sydBark()
This prints
此打印
Roger barked!
Syd barked!
As you can see, the state of the variable say
is linked to the function that’s returned from prepareBark()
.
如您所见,变量say
的状态链接到从prepareBark()
返回的函数。
Also notice that we redefine a new say
variable the second time we call prepareBark()
, but that does not affect the state of the first prepareBark()
scope.
还要注意,我们第二次调用prepareBark()
时重新定义了一个新的say
变量,但这不会影响第一个prepareBark()
范围的状态。
This is how a closure works: the function that’s returned keeps the original state in its scope.
这是闭包的工作方式:返回的函数将原始状态保持在其作用域内。
javascript闭包