dt_
dt_

Reputation: 95

Function from other file is not defined

I wrap by $(function) both files for running code when page is ready. But for some reasons calling function from first file in second file gives me error "ReferenceError: test is not defined".

First file:

$(function() {

    function test() {
        alert(1);
    }

});

Second file:

$(function() {

    test();

});

Upvotes: 1

Views: 3514

Answers (1)

Mohamed Abbas
Mohamed Abbas

Reputation: 2278

This is because JavaScript scope, you can avoid this by using Window global object.

Adding your variables to Window object will make them global, so you can access them from anywhere.

First file:

$(function() {

    window.test = function () {
        alert(1);
    }

});

Second file:

$(function() {

    test();

});

Upvotes: 7

Related Questions