Reputation: 9555
Is this a closure in JavaScript?
var test = function(b){
var a = 1;
return function(b){
a + b
}
};
var c = test(2);
Upvotes: 0
Views: 139
Reputation: 2971
var a; and parameter b of the outer function are part of the closure of the inner function. For detailed explanation of closures have a look in the FAQ
var test = function(b){ // <= param b is part of the closure of the inner function
var a = 1; // <= a is part of the closure of the inner function as well
return function(b){ // <= the inner function
a + b // <= here you are just add ind a and b together
// return a + b; //would be more appropriate
}
};
var c = test(2);
Upvotes: 0
Reputation: 1083
A closure is introduced then you define a function within test that returns local properties of the test function. an example of a closure would be here:
;(function() {
var local = 123
window.foo = function() {
return local
}
})()
What you're pretty close to in your example is currying, which involves a function that returns a function to take a second parameter. e.g:
function add(a) {
return function(b) {
return a + b;
}
}
add(5)(6) // 11
Upvotes: 2