Is this a closure in JavaScript?
var test = function(b){
var a = 1;
return function(b){
a + b
}
};
var c = test(2);
Is this a closure in JavaScript?
var test = function(b){
var a = 1;
return function(b){
a + b
}
};
var c = test(2);
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
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);
var globalVar = "xyz";
(function outerFunc(outerArg) {
var outerVar = 'a';
(function innerFunc(innerArg) {
var innerVar = 'b';
console.log(
"outerArg = " + outerArg + "\n" +
"innerArg = " + innerArg + "\n" +
"outerVar = " + outerVar + "\n" +
"innerVar = " + innerVar + "\n" +
"globalVar = " + globalVar);
})(456);
})(123);
Note in this way no return require
var globalVar = "xyz";
function outerFunc(outerArg) {
var outerVar = 'a';
var r3= function innerFunc(innerArg) {
var innerVar = 'b';
console.log(
"outerArg = " + outerArg + "\n" +
"innerArg = " + innerArg + "\n" +
"outerVar = " + outerVar + "\n" +
"innerVar = " + innerVar + "\n" +
"globalVar = " + globalVar);
};
return r3;
};
var r=outerFunc(123);
r(456);
var r=outerFunc(123); ...here we have called outer-function and assign this result return in r variable we cannot use inner function directly. we have to call outer function and assign their return in varible because above code return function