DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

A JavaScript Closure Demo


下面的代码演示了JavaScript中的闭包:

$ cat test.js
x = 100;
inc = function(){
  var x = 0;
  return function(){
    console.log(x++);
  };
};
inc1 = inc();
inc2 = inc();

$ node
> require('./test.js')
{}
> x
100
> inc
[Function]
> inc1
[Function]
> inc2
[Function]
> inc1()
0
undefined
> inc1()
1
undefined
> inc1()
2
undefined
> inc2()
0
> inc2()
1
undefined
> inc2()
2
undefined
> inc2()
3
undefined
> inc2()
4
undefined
> inc1()
3
undefined
> inc()
[Function]
> inc()()
0
undefined
> inc()()
0
undefined

可以看到inc2()最后一次执行时内部x值为4, inc1不受影响,执行时依然从上次的2开始增加变成3, 所以,不同的闭包(这里是inc1和inc2)保存了自己单独的内部变量x, 其中一个变化不会影响另一个的值。

由于每次执行inc()返回一个新的function,所以每次执行inc()()都打印0。

参考:

javascript的闭包的概念和ruby的闭包的概念有何异同?.

"Load and execute external js file in node.js with access to local variables?" on StackOverflow.



Published

Sep 16, 2015

Last Updated

Sep 16, 2015

Category

Tech

Tags

  • closure 3
  • javascript 11

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor