js closure

js closure

 

scope:

in js, inner function has access to params/local variable of the outer function,

 

closure:

variable use the scope where they are defined, even apparently the scope is finished,

inner function:

a inner function will always has access to the scope which defined it - the outer function, even after the outer function already finished execution,

 

when to use closure:

usually used with inner function, for:

* access local variable even after it outer function execution finished,

* make variable private, only could be accessed by the inner function,

 

------

e.g.

 

example 1:

	var scope = "global scope";
	function checkscope() {
	    var scope = "local scope";
	    function f() { return scope; }
	    return f;
	}
	checkscope()();	// => "local scope"
 

example 2:

	var uniqueInteger = (function() {
		var counter = 0;
		return function() { return counter++; }; // the returned function is the only one who can access the counter variable,
	}());
	for(var i=1;i<5;i++) {
		console.log(uniqueInteger());
	}
 

 

example 3:

	function counter() {
		var n = 0;
		return { // the returned object, is the only one who has access to the variable n,
			count: function() { return n++; },
			reset: function() { n = 0; }
		};
	}
	var n1 = counter();
	var n2 = counter();

	console.log(n1.count());
	console.log(n2.count());
	console.log(n1.count());
	console.log(n2.count()); // n1 & n2 has separate scope, they has different n, and don't effect each other,

	n1.reset(); 
	console.log(n1.count());
	console.log(n2.count());
 

 

------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值