10

what is the rule around calling functions from one js to another ? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file.

Is there some rule around ordering or some trick you have to do to get this to work?

3 Answers 3

31

It has to be accessible in the global scope somewhere. For example:

// file1.js
function hello() {
    alert("Hello, world!");
}
// file2.js
$(function() {
    hello();
});

Likely, you have something like this:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    // ...
});
// file2.js
$(function() {
    hello();
});

hello is only in scope of the closure defined in file1.js. Therefore, to access it in file2.js, you'd have to export it to somewhere where file2.js can get at it:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    window.hello=hello;
});
// file2.js
$(function() {
    hello();
});

Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script.

Sign up to request clarification or add additional context in comments.

Comments

7

Are you calling the function in an event handler, or immediately when the javascript file is loaded? If it's not in an event handler, then load order is important. If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad listener.

1 Comment

so if it is coming from an event handler, i dont need to worry ??
3

The browser parses the javascript files in the order they appear in the HTML. So if a function that is excecuted in the first file relies on a function that is in the second file it won't work. If you use $(function() {}); for example with jQuery this is instructing the javascript to wait until the onload event is fired from the window object. This ensures all the elements on the page have been loaded prior to execution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.