var a = 1;
function b(x) {
var c = 2;
return x * c;
}
Javascript closures help solving that issue by tying a function with a context:
function a(x) {
return function b(y) {
return x + y;
}
}
var c = a(3);
var c = function b(y) {
return 3 + y;
}
var d = c(4);
REM: If someone modifies the value of x (say x = 22) after the instance of function b has been created, this will be reflected in b too. Hence a later call to c(4) would return 22 + 4, that is 26.
Closures can also be used to limit the scope of variables and methods declared globally:
(function () {
var f = "Some message";
alert(f);
})();
Now, there is a common Javascript caveat where closures can help:
var a = new Array();
for (var i=0; i<2; i++) {
a[i]= function(x) { return x + i ; }
}
a[0] = function (x) { return x + 0 ; }
a[1] = function (x) { return x + 1 ; }
a[2] = function (x) { return x + 2 ; }
In reality, this is how a is initialized, since the last value of i in the context is 2:
a[0] = function (x) { return x + 2 ; }
a[1] = function (x) { return x + 2 ; }
a[2] = function (x) { return x + 2 ; }
var a = new Array();
for (var i=0; i<2; i++) {
a[i]= function(tmp) {
return function (x) { return x + tmp ; }
} (i);
}
No comments:
Post a Comment