Javascript Closure
来源:互联网 发布:vggnet 网络结构 编辑:程序博客网 时间:2024/05/16 06:10
Simple example of closure:
function sayHello(name) { var text = 'Hello ' + name; // local variable var sayAlert = function() { console.log(text); } return sayAlert;}var say = sayHello( "fefefe");say();sayAlert holds a reference to text. text as a local variable is accessible outside of the scope
In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.
In JavaScript, if you declare a function within another function, then all the local variables including parameters can remain accessible after returning from the function you called.
Local variables are not copied but referenced by closure
function say667(){var num = 666;var sayAlrt = function(){alert(num);}num++;return sayAlert;}var sayNumba = say667();sayNumba();//667
Useful example:
// Define a function that sets a DOM node's color// to yellow and then fades it to white.var fade = function (node) { var level = 1; var step = function ( ) { var hex = level.toString(16); node.style.backgroundColor = '#FFFF' + hex + hex; if (level < 15) { level += 1; setTimeout(step, 100); } }; setTimeout(step, 100);};fade(document.body);
Avoid creating functions in the LOOP, because function returned will always be the same!
Tutorial and reference: http://www.javascriptkit.com/javatutors/closures.shtml
- JavaScript - Closure
- Javascript Closure
- javascript Closure
- JavaScript Closure
- Javascript Closure
- javascript closure
- JavaScript closure
- javascript closure
- [JavaScript] Closure In JavaScript
- 诡异的JavaScript Closure
- 诡异的JavaScript Closure
- Javascript Closure[1]
- Javascript Closure[2]
- javascript 之 Closure
- Javascript闭包(Closure)
- Javascript--闭包(closure)
- Javascript闭包(Closure)
- 在Javascript中闭包(Closure)
- Javascript Exception
- Javascript OOP augmenting with prototype
- 背包总结
- QWT在win7下的安装说明
- 使用QWT产生error LNK2001的原因及解决方案
- Javascript Closure
- 集训第三周
- 黑马程序员——集合学习日志
- YouTube视频播放器采用了HTML5
- struts2的ajax实现
- Windows 8 Store应用开发XAML实例教程系列汇总
- awr report
- Vaadin Web应用开发教程(18):UI组件-Table 组件
- springMai的html文本和附件的传递、解决html中文乱码、解决附件的中文名字乱码