闭包的好处是什么,它们通常何时使用? [英] What are the benefits of a closure, and when are they typically used?

查看:161
本文介绍了闭包的好处是什么,它们通常何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名网络开发人员,但很多人都在寻找稍微更先进的技能,而且了解闭包似乎是这方面的前沿。

I'm a web developer, but lots of folks are looking for slightly more advanced skills and understanding closures seems to be at the forefront of this.

整个执行上下文创建一个引用一个变量,没有被毁灭的东西,但真的,这是某种类型的私人或静态变量实现JavaScript?

I get the whole "execution context creating a reference to a variable that doesnt ever get destroyed" thing, but really, is this some sort of private or static variable implementation in JavaScript?

推荐答案

它们对许多事情都有好处,例如可见性(如传统OO中的私人成员) >

They can be good for lots of things, for example, visibility (like private members in traditional OO).

var count = function(num) {

   return function(add) {
       add = add || 1;
       num += add;
       return num;
   }

}

查看

我的 count()可以用数字播种。当我为变量赋值一个变量时,我可以使用一个可选的数字来添加到内部 num (原来是一个参数,但仍然是返回的范围的一部分函数)。

My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).

这是一个非常好的概述

  • What is a practical use for a closure in JavaScript?
  • How does a javascript closure work ?
  • When actually is a closure created?
  • more...

这篇关于闭包的好处是什么,它们通常何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆