views:

36

answers:

2

Hi

I am just wondering what is the difference between these two

File1.js
$(function()
{
   function MyFunction()
   {
         // some code here
   }
});

File2.js

$(function()
{
      // call it.
      MyFunction();
});


File1.js
function MyFunction()
{
        // some code here
}


File2.js

$(function()
{
      // call it.
      MyFunction();
});

So what is the difference? When I did the first way and I tried to call MyFunction() from File2.js it never worked. I moved my function out of the Jquery.Document ready in File1.Js and it worked.

I have some other functions that are in File1 and even though they are in document ready anything in File1 can seem to call it no problem.

It just seems like across script files it has a problem calling functions when setup that way.

+2  A: 

In ECMAScript there is only function ( no block scope ) scope, and anything defined within a function with 'var' or the 'function' keyword will not be accessible outside of the scope ( unless you assign it to something from an outer scope like window ). You defined a function in another function and according to function scope rules you cannot access it.

However, you can access variables/functions defined on the outer scope, which is what you did on the second example.

So in essence what you are doing when you are $(function(){})'ing is creating a sandbox, a restricted area where if you define any variables you cannot access them unless you specifically assign them to be properties of something like the window object, which is the global namespace.

meder
Ah ok I suspected it had something to do with scope but was not sure why though. It seems kind of harder to figure out scope in Javascript files. Since Like you can have 10 different functions in 10 different scripts and if they are all referenced after each other the 11th script can access them all. But something like C# you would have to create a new object of that class to get access to them(unless of course it was a static method).
chobo2
It also made me wonder when I had 2 scripts referenced on the same page and each one had the a function with the same name and they never conflicted. So I guess since it is in the "sandbox" thats why it never conflicted.
chobo2
I am guessing if they where outside the the $(function(){}) there would be a conflict?
chobo2
If you had two functions with the same name in the same scope the one defined last would override the former.
meder
I suggest you get something like FireBug or the Spidermonkey interpreter and try this out in a REPL.
meder
+1  A: 

I believe this issue is caused because the extra "$();" wrapping the function creates a sort of closure, resulting in a limited scope.

chills42