The chicken and the egg
I have two very big functions, a
and b
, which are currently in one big JavaScript file. My goal is to have each function in a separate JavaScript file.
The problem is that a
makes calls to b
, and b
makes calls to a
, so that if I put both functions in different files, then one will be missing the definition of the other, and I get an error message and things break.
When they are in the same file, under the same closure, things don't break because of hoisting. How can I have the two functions开发者_如何学C in different files when each references the other?
If they're going to be in different files, then you won't have them in the same closure, so that's the fire problem.
After that, if you're willing to enforce load order (i.e. load A first, the B), then simply have A define a stub of B, and then B will redefine it when it loads. As long as A doesn't execute before B loads, you should be fine.
Use Google Loader, then you know the scripts are available before your function calls.
I wouldn't split them into separate files if they belong together like this. Instead, try to break up the functions themselves. Long files are no problem, but long functions are generally not maintainable.
Apart from that: if they are separate functions, it doesn't matter if they are in the same file or not, as long as both files are loaded, and you don't call the functions until both files are loaded.
You are not allowed to something like this:
a.js:
function a() {}
b();
b.js:
function b() {}
a();
Instead are only allowed to define the functions. In a third script which you include after a.js and b.js you call a()
or b()
. Then calls INSIDE of the function a
can have calls to function b
and contrariwise.
精彩评论