JavaScript closures..... the first description I read about them made no sense.
"Because an inner function might live past the call to the outer function(s) in which it was created, the outer local variables which the inner function accesses must survive with the inner function. This is called closure: the local variables of the call(s) to the outer function(s) get retained by the inner function."
huh?
I did some googling and kind of figured it out.
if we had an example:
function Person (pName) {
var _name = pName;
this.getName = function(){
return _name;
};
}
and we call:
var me = new Person("Rui")
me
# => Person {getName: function}
me.getName()
# => "Rui"
Basically, a closure is a function that has a pointer reference to a (free) variable which is something that gets deleted (falls out of scope) after the parent function has returned or executed. In this example, because _name is declared with var inside of the Person constructor, it is not accessible by outside of that function and only exists while it is running. BUT, if that outer function still has a way to reference the free var (through another function usually) it can still persist. By using a closure, we can still access the inner variable! (the purple part is the closure)
"Because an inner function might live past the call to the outer function(s) in which it was created, the outer local variables which the inner function accesses must survive with the inner function. This is called closure: the local variables of the call(s) to the outer function(s) get retained by the inner function."
huh?
I did some googling and kind of figured it out.
if we had an example:
function Person (pName) {
var _name = pName;
this.getName = function(){
return _name;
};
}
and we call:
var me = new Person("Rui")
me
# => Person {getName: function}
me.getName()
# => "Rui"
Basically, a closure is a function that has a pointer reference to a (free) variable which is something that gets deleted (falls out of scope) after the parent function has returned or executed. In this example, because _name is declared with var inside of the Person constructor, it is not accessible by outside of that function and only exists while it is running. BUT, if that outer function still has a way to reference the free var (through another function usually) it can still persist. By using a closure, we can still access the inner variable! (the purple part is the closure)