简体   繁体   English

节点:使用其他js文件的js文件的“最佳实践”

[英]Node: 'Best Practice' of js files using other js files

Here is the scenario: 这是场景:

Main.js: Main.js:

var one = require(./one.js);
var two = require(./two.js);

two.foo();

one.js: one.js:

module.exports = {
  foo: function () {
    console.log("this was called by two");
  }
};

two.js: two.js:

module.exports = {
  foo: function () {
    one.foo();
  }
};

I'm calling one of two's functions in main which then calls one's function, which then logs. 我在main中调用两个函数之一,然后调用一个函数,然后进行记录。 Currently, I get an error in two.js saying "one is not defined." 当前,我在two.js中收到一条错误消息,提示“未定义一个”。 The goal of this was to break up a giant js file into smaller ones that all use each other in some way. 这样做的目的是将一个巨大的js文件分解为较小的文件,以某种方式相互使用。 If this is not possible please let me know. 如果这不可能,请告诉我。

So far the only fixes I can think of are: 到目前为止,我能想到的唯一解决方法是:

  1. requiring one.js in two.js 在two.js中需要one.js
  2. passing an instance of one into two in some form of init function 以某种形式的init函数将一个实例传递给两个实例
  3. some global instance of one? 一个全局实例?

You need to require one.js in two.js, like you said. 如您所说,您需要在two.js中需要one.js。 Every file that accesses another file needs to require that file. 每个访问另一个文件的文件都需要该文件。

Like this: 像这样:

Main.js: Main.js:

var two = require(./two);
two.foo();

one.js: one.js:

module.exports = {
  foo: function () {
    console.log("this was called by two");
  }
};

two.js: two.js:

var one = require(./one);
module.exports = {
  foo: function () {
    one.foo();
  }
};

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

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