JavaScript - 如何了解“闭包”用法? [英] JavaScript - How do I learn about "closures" usage?

查看:94
本文介绍了JavaScript - 如何了解“闭包”用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科中的自由百科全书: Closure(computer science)

From Wikipedia, the free encyclopedia: Closure (computer science)


是一个
函数,在包含一个或多个
绑定变量的
环境中求值。当被调用时,
函数可以访问这些变量。
明确使用闭包是
与函数式编程
和语言如ML和
Lisp相关联。诸如
等其他语言中的对象的构造也可以用闭包建模成

In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Constructs such as objects in other languages can also be modeled with closures.

推荐答案

(使用jQuery的示例)

(using an example from jQuery)

function SetClassOnHover(className){
  $("td").hover(
    function () {
      $(this).addClass(className);
    },
    function () {
      $(this).removeClass(className);
    }
  );
}

当在每个范围内使用变量className时,功能。当SetClassOnHover退出时,两个函数必须在className上保留一个句柄,以便在调用函数时访问它的值。这是闭包允许的。

The closure comes into play when the variable className is used inside the scope of each function. When SetClassOnHover exits, both functions must retain a handle on className in order to access its value when the functions are called. That's what the closure enables.

这篇关于JavaScript - 如何了解“闭包”用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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