Here in late 2020, you'd use modules to do this, either relying on the native support that's present in all modern major browsers, or bundlers like Webpack or Rollup.js that take code using module syntax and bundle it for older browsers.
With module syntax, in the simple case, you'd export the function you want to provide:
export function date_of_birth(/*...*/) {
// ...
}
That's an exported function declaration, which creates a named export. Code in another module that wanted to use that function would import that function:
import { date_of_birth } from "./module-name.js";
There's a lot more to this topic, more on MDN or in Chapter 13 of my book JavaScript: The New Toys (links in my profile if interested).
Old answer:
In your original code, it's undefined because it's not a global. When you define a function within another function, as I take it you've done, like this:
$(document).ready(function() {
function date_of_birth(target, selector, days) { // Do something }
});
...the function is only accessible within that ready
callback, not globally.
When you changed it to:
$(document).ready(function() {
window.date_of_birth = function date_of_birth(target, selector, days) { // Do something };
});
that does indeed make it a global, so the error tells us that the ready
callback for the other file (where you're using the function) runs before the ready
callback in that file (where you're defininig the function).
How to fix it:
Pick a unique identifier for your app, say MyApp
. (It doesn't have to be globally unique, it just has to A) Not be something defined in the browser environment, B) Not be something likely to be defined in the browser environment at some point in the future, and C) Not be something defined by any lib you use.) For instance, jQuery uses jQuery
.
In your file where you define this function, do this:
var MyApp = MyApp || {};
MyApp.date_of_birth = function date_of_birth() { /*...*/ };
Or if you have shared functions for class-wide data or something that you want to keep private, you could use a wrapper function:
var MyApp = MyApp || {};
(function() {
function privateWorkerFunction() {
}
MyApp.date_of_birth = function date_of_birth() { /*...*/ };
// ...
})();
In your file where you use that, use it like this:
MyApp.date_of_birth(/*...*/);
Ensure that the file defining the function is before the file using it, put both at the end of the HTML (just before the closing </body>
tag), and get rid of the ready
callbacks (there's no need; if the scripts are at the end of the document, things are ready enough).