Jquery function not defined - scope issue?

I have a pretty simple problem that I need help with.

I have two js files that I uploaded to a page via a tag in html. All code in both of these files is executed / loaded within $(document).ready();

In a specific event, function A, defined in the first file, tries to call function B, defined in another file. However, this fails, I get an error that function B is not defined.

I notice that if I take the definition of function B outside of $(document).ready() , this function A will be able to call function B - it is in scope.

Why?

+4
source share
1 answer

This is a problem with the area. Everything that is defined inside a function is available only inside this function, unless it is made global in some other way. When you move a function outside of the ready function, it becomes global, making it available around the world.

EDIT: When I say "made global in some other way," I mean something like this:

 window.something = "something"; 

This will create the global variable something , even if this line of code exists in your finished function.

+3
source

Source: https://habr.com/ru/post/1388545/


All Articles