Javascript Closure

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值