当前位置: 代码迷 >> JavaScript >> 一个函数嵌套另一个函数算不算闭包?解决方案
  详细解决方案

一个函数嵌套另一个函数算不算闭包?解决方案

热度:190   发布时间:2013-11-11 14:02:17.0
一个函数嵌套另一个函数算不算闭包?
本帖最后由 WildGhost 于 2013-11-08 11:18:09 编辑
一讲到闭包,通常就是类似下面的例子――

var generateClosure = function() { 
var count = 0; 
var get = function() { 
count ++; 
return count;
}; 
return get; 
}; 
var counter = generateClosure(); 


有的人甚至说,只有从一个函数里返回另一个函数才能算是闭包。

但是根据《Professional Javascript for Web Developers》的定义――
Closures are functions that have access to variables from another function’s scope. This is often accomplished by creating a function inside a function.

犀牛书――
Technically, all JavaScript functions are closures: they are objects, and they have a scope
chain associated with them.

那下面这段代码算不算产生了闭包?

var generateClosure = function() { 
var count = 0; 
var get = function() { 
console.log(count); 
}; 

get(); 
}; 
generateClosure(); 

------解决方案--------------------
产生过。又销毁了。
不会用调试器,看更多书也没用。
  相关解决方案