定义:javascript
a function use a variable outside the scope are closures.java
或者说面试
"Closures are FUNCTIONS WITH PRESERVED DATA"闭包
console.dir()异步
Displays an interactive(交互式) list of the properties of the specified JavaScript object. ide
syntax:console.dir(object);函数
var addTo = function(passed) {this
var inner = 2;spa
return passed + inner;3d
};
console.log(addTo(3));
//5
in Javascript:, you can do this without passing variables:
example1:
var passed = 3;
var addTo = function(){
var inner = 2;
return passed + inner;
};
console.log(addTo(3));
This is a closure.
JS use lexical scoping. means inner variables is not accessible outside but anything defined outside is automatically avaliable inside the function.
定义:
a function use a variable outside the scope are closures.
function is also object in javascript,so in Chrome, console.dir(addTo(3))
example2:
var addTo = function(passed){
var add = function(inner){
return passed + inner;
};
return add;
};
console.dir(addTo(3));
var addFour = new addTo(4);
console.dir(addFour);
console.log(addFour(2))
...
面试中通常会提到下面这种闭包的用法:
function fun(){
var x = 1;
return function(){
x++;
console.log(x);
}
}
var a = fun();
a();
a();
a();
...这种用法演示了闭包的一种做用——在函数外面对函数内变量进行操做..
还有一种用法就是在for()循环中若是嵌套了异步事件。
for(let i = 0; i<10 ;i++)
{
setTimetou(()=>{console.log(i)},0);
}
这样打印出10个10,
若是改为
for(let i =0;i<10;i++)
{
(function()
{
setTimeout(()=>{console.log(i)})
})()
}
也就是说在setTimeout外面加了个函数,函数会向外面寻找这个i变量,这时其实造成了一个闭包。
"FUNCTIONS WITH PRESERVED DATA“
那么问一下,若是咱们打印 console.dir(a)
在Chrome控制台中Closure是谁呢?
固然是fun函数啦
不信咱们打印看一下:
这个函数中保留了数据x,
最后再来看一下文章最开头最原始的定义
"FUNCTIONS WITH PRESERVED DATA“
保留了数据的函数。
WIKI上闭包的定义:
直译过来:
闭包是一个函数 这个函数的非本地变量被绑定关联到value(或者理解为 这个函数的内部变量和外部变量关联起来了)( 这个函数引用了外部的变量)