This is so-called closure!
JS function has its own scope: variables defined inside a function cannot be visited outside it. If you want to do so, you must have a reference to it from the outer scope.
var globarF1;
$(function(){
f1();//OK
f2();//OK
function f1(){
console.log("1");
}
globarF1 = f1;
});
globarF1();// now it's ok
Here's a more interesting example:
function outer() {
var asdf = 1;
return function() {
return asdf;
}
}
asdf; // Error: asdf is not defined
var qwer = outer();
qwer(); // 1
Notice that outer()
just returns an amounymous function, qwer()
actually executes the amounymous function, and this is the power of closure: function outer
's execution scope is not destroyed even if it has returned, because there is a reference to its local variable from outside, and you can visit the variable asdf
inside it in this way.