简体   繁体   English

从一个js文件到另一个js文件调用函数的问题

[英]Problems with calling function from one js file to another

In the file data.js i have: 在文件data.js我有:

(function () {

   data() 

   function runThisWhenDataIsFinished() {

        console.log("Works!"); 

   }


})();

In the file app.js i have 在app.js文件中我有

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. 当我调用data()时,我收到消息“我在数据函数中”,当我尝试调用runThisWhenDataIsFinished()方法时,我得到错误:runThisWhenDataIsFinished()方法未定义。

So how can i access runThisWhenDataIsFinished method in data.js from app.js? 那么如何从app.js访问data.js中的runThisWhenDataIsFinished方法呢?

Best regards 最好的祝福

You can't do this because runThisWhenDataIsFinished is lexically scoped (to it's parent function). 你不能这样做是因为runThisWhenDataIsFinished是词法范围的(它的父函数)。 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 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. 它们并不是在不同的文件中,而是runThisWhenDataIsFinished()在匿名函数中。 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. 如果你将它移到函数之外,只要在进行data()调用之前加载了data.js它就会正确运行它。

A few comments : 一些评论:

  • first, you define "runThisWhenDataIsFinished" after calling the "data()" function ; 首先, 调用“data()”函数定义“runThisWhenDataIsFinished”; 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. 如果在定义函数后调用“data()”事件,则它将无法工作,因为,如果以其他方式解释,它将仅在匿名函数的范围内定义。

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. 正如所指出的,我建议您查看Module模式以了解您真正想要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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