【问题标题】:Calling one nodejs module from the other从另一个调用一个nodejs模块
【发布时间】:2018-03-22 14:37:52
【问题描述】:

我有以下设置,test.html、test_bar.js、test_foo.js:

   /* test_bar.js */
    BAR = {
      init: function() {
         console.log("BAR LOADED!");
         /* I'd like to call FOO.hello(); here */
      }
    };

    $(function() {
      $(window).load(function() {
        BAR.init();
      });

    });

    /* test_foo.js */
    FOO = {
      init: function() {
       console.log("FOOO LOADED");
       },
      hello: function(){ 
       console.log("hello I'm FOO");
      }
    };

    $(function() {
      $(window).load(function() {
        Foo.init();
      });

    });
    <!DOCTYPE html>
    <html>
    <head>
    	<title>FOO BAR HELP</title>
    </head>
    <body>

    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/test_bar.js"></script>
        <script src="js/test_foo.js"></script>
    </html>

我不断收到以下错误:

未捕获的 ReferenceError:未定义 Foo 在 test_foo.js:9 调度时(jquery.min.js:3) 在 r.handle (jquery.min.js:3)

我怀疑这是因为我正在执行 window.load,两次(每个 .js 中一次)并试图在 FOO 加载之前调用它。我应该注意到代码库是继承的,我想将 FOO 和 BAR 保存在单独的 .js 文件中。

如何重构设计,以便可以调用诸如 FOO.hello(); 之类的函数来自酒吧?

谢谢

【问题讨论】:

  • Foo vs FOO 看起来像是一个错字。
  • 正确!谢谢!!

标签: jquery node.js


【解决方案1】:

您将对象名称定义为 FOO,但将其称为 Foo。

FOO = {
    init: function() {
        console.log('foo loaded');
    }
}

$( function() {
    FOO.init(); // "foo loaded"
});

如果您想在 BAR 中调用 FOO,那么您必须在 BAR 之前包含 FOO,如下所示:

<script src="js/test_foo.js"></script>
<script src="js/test_bar.js"></script>

【讨论】:

  • 如果这就是问题的全部,那么这个问题可能会由于拼写错误而被关闭,没有得到回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 2018-11-22
  • 1970-01-01
相关资源
最近更新 更多