简体   繁体   中英

Problems with calling function from one js file to another

In the file data.js i have:

(function () {

   data() 

   function runThisWhenDataIsFinished() {

        console.log("Works!"); 

   }


})();

In the file app.js i have

function data() {

    console.log("Im in the data function");

    runThisWhenDataIsFinished();

}

When i call on data() i get the message "Im in the data function", when i try to call on the runThisWhenDataIsFinished() method i get error: runThisWhenDataIsFinished() method is not defined.

So how can i access runThisWhenDataIsFinished method in data.js from app.js?

Best regards

You can't do this because runThisWhenDataIsFinished is lexically scoped (to it's parent function). If you want to be able to access it outside of that scope you will have to use some sort of global namespace.

See http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

It's not so much that these are in different files, but that runThisWhenDataIsFinished() is in an anonymous function. If you move this outside of the function, as long as data.js has been loaded before making a data() call it will run it correctly.

A few comments :

  • first, you define "runThisWhenDataIsFinished" after calling the "data()" function ; so there is no way the function is defined

  • event if you call "data()" after defining the function, it will not work, because, as explaied otherwise, it will only be defined in the scope of the anonymous function.

There is something that would work, but do not do that :

function data() {

  console.log("Im in the data function");

  // The 'globalRunThisWhenDataIsFinished' function is no defined in this scope, 
  // so it will only be called if it exists as a *global* variable
  globalRunThisWhenDataIsFinished();

}

(function () {

   // When calling the anonymous function like you do, 
   // 'this' is the Window object, so you can add "global" variables
   // like this. However you probably DO NOT WANT TO DO THAT
   this.globalRunThisWhenDataIsFinished = function() {

      console.log("Works!"); 

   }

   data();

})(); 

As pointed out, I suggest you look at the Module pattern to understand what you really want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM