-1

Here is the jsfiddle. Code:

$(function(){
    f1();//OK
    f2();//OK
    function f1(){
        console.log("1");
    }
});

function f2(){
    console.log("2");
}

f2();//OK
f1();//NO!!!

As you can see, the f1() is not executed from globe scope(or outside jquery scope). Could some one tell me why?

SPG
  • 6,109
  • 14
  • 48
  • 79

2 Answers2

3

Functions declared within other functions are ONLY available within the function in which they are declared. They are like local variables in that regard. They are private to the scope in which they are declared and there is no way to access them from the outside.

If you want it available in a higher scope, then declare the function in the higher scope or assign it to a higher scope and then you can call it from both places.

$(function(){
    f1();//OK
    f2();//OK
});

function f1(){
    console.log("1");
}
function f2(){
    console.log("2");
}

f2();//OK
f1();//OK

It's also possible to do this (manually assigning a function into the global scope):

$(function(){
    // assign function into the top level scope
    window.f1 = function(){
        console.log("1");
    }

    f1();//OK
    f2();//OK
});

function f2(){
    console.log("2");
}

f2();//OK
f1();//OK - only after document is ready and window.f1 has been assigned
jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

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.

Leo
  • 13,428
  • 5
  • 43
  • 61
  • I knew closure for a long time, but haven't used it yet. This is a very good example, thx! – SPG Dec 04 '14 at 06:21
  • @nich updated answer with a more interesting example. closure is commonly used in js to protect variables and restrict the approach to modify them. – Leo Dec 04 '14 at 06:33