A Javascript closure is when an inner function is inside of an outer function (a function inside a function). The inside function has access to
1. Variables defined in the outer function
2. Argument passed into the outer function
var CreateExample= function(example){
return function(text){
console.log(example +" "+ text);
}
};
var example1= CreateExample("Hi");
var example2= CreateExample("Hello");
example1("test one"); //Hi test one
example2("test two"); //Hello test two.
In most object oriented languages like java/c#, when you reach return all variables declared inside that function get destroyed and memory is freed up.
IN javascript, when creating a closure and return as function, all local variable will remain in memory and accessible.
1. Variables defined in the outer function
2. Argument passed into the outer function
var CreateExample= function(example){
return function(text){
console.log(example +" "+ text);
}
};
var example1= CreateExample("Hi");
var example2= CreateExample("Hello");
example1("test one"); //Hi test one
example2("test two"); //Hello test two.
In most object oriented languages like java/c#, when you reach return all variables declared inside that function get destroyed and memory is freed up.
IN javascript, when creating a closure and return as function, all local variable will remain in memory and accessible.
Comments
Post a Comment