前端学习笔记饥人谷技术博客首页投稿(暂停使用,暂停投稿)

JavaScript闭包再谈

2016-03-13  本文已影响660人  转角遇见一直熊

虽然前面写过一篇文章说闭包JavaScript模块化和闭包,但是一位美女程序员朋友讨论的时候好像并不能理解那边文章中C代码和Javascript代码的区别,因为她是并没有学过C,所以我觉得还是单纯的从JavaScript的角度来讨论一下闭包,如果有什么不对的地方,欢迎大家指教。

如果知道下面两段代码运行结果的人,可以不看此文。

例子1

var x = 10;
function fn(){
    console.log(x);
}

function show(f){
    var x=20;
    (function(){
        f();
    })();
}
show(fn);
//输出10

例子2

function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }

自由变量

我们先看看MDN上对闭包的定义。

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

这里有个地方比较让人读不懂:
闭包是指函数有自由独立的变量。什么叫自由独立的变量啊,这句话真让人费解。
想弄清楚,我们看一个例子。

function f(x) {
    function g() {
        return x;
    }
    return g;
}

//Tell f to create a new g
var g5 = f(5);

//g5 is a function that always returns 5
alert(g5());

//Tell f to create another new g
var g1 = f(1);

//g1 is a function that always returns 1
alert(g1());

g5和g1是两个不同的函数,他们碰巧有相同的代码,但是他们在不同的环境中执行,有不同的自由变量。对上面的自由变量的解释:
如果一个作用域A被另一个作用域B包括,那么在B作用域中定义的变量在A中就是自由的(拗口)。

上面的例子中,

  1. x在g作用域中就是自由的,所以g可以使用他,因为x是在f作用域中定义的,f的作用域包括了g的作用域。
  2. 全局变量在f作用域和g作用域都是自由的。
  3. 相反x在f以外就不可见,显然显的“不自由”了。。。这大概就是自由的含义吧。。。
  4. 真正的自由变量理解可以看看这个文章Free_variables_and_bound_variables

In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function.[1]
The term non-local variableis often a synonym in this context.
不是本地变量+不是参数=》自由变量

作用域链

不管什么时候访问一个变量,js解析器就在当前scope中找它,如果变量在当前作用域没有定义,解析起就在包括当前作用域的更大的作用域中查找,一直到全局作用域还没找到,抛出ReferenceError。这种行为像不像链条呢,这个链条就叫作用域链,不清楚的朋友可以复习一下JavaScript模块化和闭包这篇文章。

闭包定义

所以对定义的解释可以理解为

  1. 闭包是引用到上层作用域的自由变量的那个函数对象,换句话说如果一个函数引用到自由变量了,可以说这个函数对象是闭包;
  2. 不过英文定义的第二句说:定义这个函数的环境(上下文)是闭包(In other words, the function defined in the closure 'remembers' the environment in which it was created.),
  3. 总之,MDN的英文定义就说的这个意思,我觉得还是不清晰的定义,两句话,一个说函数在一定情况下是闭包,一个说是定义函数的环境是闭包。如果有高人可以留言解释一下到底哪个是定义,反正我认为闭包是引用到上层作用域的自由变量的那个函数对象算是定义吧。

父作用域是哪个作用域啊

看到下面代码很吃惊的朋友可能不知道静态作用域是何物。看看定义吧Scope_(computer_science)

静态作用域

In languages with lexical scope (also called static scope), name resolution depends on the location in the source code and the lexical context, which is defined by where the named variable or function is defined. 名称查找依赖于定义位置。

这个父作用域指的是函数声明的那个作用域。不是调用函数的地方。所以上面代码输出为10。


循环中创建闭包

另外,美女程序员还对在循环中创建闭包不是很理解。
我们看看这个例子

<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}

setupHelp();

这个例子中,item在onfocus指向的函数中是自由的,但是onfocus是有很多个的,指向的函数也是定义个很多次,但是item却始终是父作用域中的那个item,所以所有的onfocus中的item都是同一个。

在看看怎么修复:

function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function makeHelpCallback(help) {
  return function() {
    showHelp(help);
  };
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus =
       makeHelpCallback(item.help);
  }
}

setupHelp();

现在在中间加了一层makeHelpCallback,在makeHelpCallback中,help在return的匿名函数中是自由变量,makeHelpCallback被调用很多次,产生了多个不同的help,showHelp中记住的是外部不同的help变量,但是makeHelpCallback中记住的外部变量item.help始终是一个。


闭包

虽然闭包的概念可谓很基础,但是却又是很关键,想了解语言设计方面的知识可以看看这些文章(打不开请开vpn):
First-class function
想知道JS为啥牛逼可以看这个
why-javascript-is-awesome

上一篇下一篇

猜你喜欢

热点阅读