-1

I am writing one function called test function inside external java script file. inside document ready function, i write one function which is not accessible from another java script declared in another html page and calling from outside document ready function and if I declared function test function outside document ready then its working properly.

Swapnil
  • 654
  • 7
  • 27
  • this is not an issue, you are declaring a function inside of a closure. – cecilozaur Jan 28 '14 at 12:09
  • sorry for the incomplete answer, by doing what you are doing you are declaring the function inside of a closure: `http://stackoverflow.com/questions/111102/how-do-javascript-closures-work` and that function will only be available within that closure – cecilozaur Jan 28 '14 at 12:14
  • Is any another method to call that function? Or it is impossible in that closure – Swapnil Jan 28 '14 at 12:19
  • maybe if you return a reference to the function from the closure – cecilozaur Jan 28 '14 at 12:32

1 Answers1

0

There are a couple of things to note here:

\1 Function names are variables with a function assigned as their value. So, the following two things are practically the same:

function my_func = function () {
    alert('Hello World!');
};

var my_func = function () {
    alert('Hello World!');
}; 

\2 Variable scoping in javascript: variables declared inside of a closure are visible only to that closure. However, a closure has access to variables declared in a higher scope. So, the following will not work:

var my_func = function () {
    var my_second_func = function () { alert ('hello');};
};
my_func();
my_second_func(); // not declared

But the following will work:

var my_second_func; // declare the variable in the global scope
var my_func = function () {
    my_second_func = function () { alert ('hello');};
};
my_func();
my_second_func(); // will alert "hello"

Note where the var keywords are. These declare a variable in the current scope. If you want to be absolutely sure that the function is available in the global scope, declare it this way:

window.my_function = function () {
    // do something
};

However, this is generally considered bad practice and should be used sparingly.

Matt
  • 1,287
  • 2
  • 11
  • 25