闭包 (Closure)

定义:

a function use a variable outside the scope are closures.

 或者说

"Closures are FUNCTIONS WITH PRESERVED DATA"

 

 

 

console.dir()

Displays an interactive(交互式) list of the properties of the specified JavaScript object. 

syntax:console.dir(object);

 

 

var addTo = function(passed) {

       var inner = 2;

       return passed + inner;

};

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(或者理解为 这个函数的内部变量和外部变量关联起来了)( 这个函数引用了外部的变量)

 

 

 

 

 

资料1: https://stackoverflow.com/questions/2800463/how-variables-are-allocated-memory-in-javascript/10618981#10618981

 

posted @ 2018-05-05 11:23  hh9515  阅读(240)  评论(0编辑  收藏  举报