javascript闭包_JavaScript闭包说明

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.

这是闭包的工作方式:返回的函数将原始状态保持在其作用域内。

翻译自: https://flaviocopes.com/javascript-closures/

javascript闭包

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值