javascript - Function from other file is not defined - Stack Overflow

admin2025-04-21  0

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();

});

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();

});
Share Improve this question edited Nov 18, 2017 at 9:31 jhpratt 7,13016 gold badges42 silver badges53 bronze badges asked Nov 18, 2017 at 5:37 dt_dt_ 951 silver badge11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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();

});

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745171946a288710.html

最新回复(0)