How to use js closure
这篇文章主要为大家展示了"js闭包怎么用",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"js闭包怎么用"这篇文章吧。
首先引用来自官网文档的定义:
closure is the combination of a function and the lexical environment within which that function was declared.
闭包是一个函数和其内部公开变量的环境的集合.
简单而言, 闭包 = 函数 + 环境
第一个闭包的例子
function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure alert(name); // use variable declared in the parent function } displayName(); }init();because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
其实这个栗子很简单,displayName()就是init()内部的闭包函数,而为啥在displayName内部可以调用到外部定义的变量 name 呢,因为js内部函数有获取外部函数中变量的权限。
第二个例子
var data = [ {'key':0}, {'key':1}, {'key':2}];function showKey() { for(var i=0;i