定義: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(或者理解爲 這個函數的內部變量和外部變量關聯起來了)( 這個函數引用了外部的變量)