Hi guys, can you enlighten me as to wht is happening here, is my thinking correct:
function foo() {
var a = 2;
function bar() {
console.log( a );
}
return bar;
}
var baz = foo();
baz(); // 2
When foo(); is assigned to var baz (var baz = foo(); ) foo(); runs and assigns function bar(); to baz(); so running baz(); is as if we are running bar(); outside of the scope it was declared in, but because of closure function bar(); which is now theoretically baz(); has closure over the scope of foo(); so it can access the “var a” variable.
Is this correct?
So if we did this:
function foo() {
var a = 2;
function bar(x) {
console.log( a + x );
}
return bar;
}
var baz = foo();
baz(3); // 5
in this example is it correct to assume after foo(); is assigned to var baz, baz(3); becomes equivilent to running bar(3); from outside the scope it was declared in.
I understand that you can ot run bar(); outside of the function it was declared in so I am assuming the only way to achieve this is to assign foo(); to var baz (var baz = foo(); ).