【问题标题】:Access function in another module.export in a separate file访问另一个模块中的函数。在单独的文件中导出
【发布时间】:2012-11-13 18:49:54
【问题描述】:

我有几个 javascript 文件,其中包含我的节点应用程序的不同部分。使用以下逻辑需要它们。我想从 file2.js 访问一个 file1.js 中的函数,但到目前为止收效甚微。任何帮助将不胜感激,谢谢。

app.js:这是我启动服务器并包含所有快速路由的文件。

require(path_to_file+'/'+file_name)(app, mongoose_database, config_file);  //Require a bunch fo files here in a loop.

file1.js:这是使用上述代码所需的示例文件。

module.exports = function(app, db, conf){
  function test() {  //Some function in a file being exported.
    console.log("YAY");
  }
}

file2.js:这是使用上述代码所需的另一个文件。我想从这个文件 (file2.js) 中访问 file1.js 中的一个函数。

module.exports = function(app, db, conf){
  function performTest() {  //Some function in a file being exported.
    test();
  }
}

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    file1.js

    module.exports = function(app, db, conf){
      return function test() {
        console.log("YAY");
      }
    }
    

    注意你需要返回函数。

    file2.js

    module.exports = function(app, db, conf){
      return function performTest() {
        var test = require('./file1')(app, db, conf);
        test();
      }
    }
    

    (一些其他文件)

    var test = require('./file2')(app, db, conf);
    test();
    

    require('./file2')(app, db, conf)();
    

    【讨论】:

    • 感谢您的回复。如果我在 module.export 中有一个函数,则此方法有效,但是如果我在 module.export 中的文件中有多个函数,我如何访问这些函数。有没有办法访问这样的功能:var file1 = require('./file1')(app,db,conf); 然后file1.test()
    • 当然。只需让您导出的函数返回一个具有属性test 的对象,其值是一个函数。来自this 问题的讨论可能会有所帮助。
    【解决方案2】:

    您现在在 file1 中拥有的功能仅适用于导出中的功能。相反,您希望导出一个对象,其中每个函数都是该对象的成员。

    //file1.js
    module.exports = {
        test: function () {
        }
    };
    
    
    //file2.js:
    var file1 = require('./file1.js');
    module.exports = {
        performTest: function () {
            file1.test();
        }
    }
    

    【讨论】:

    • 嘿,我尝试过使用这种方法,但我无法让它发挥作用。如果我使用您的确切语法,我会在 funtion 单词后面的意外括号 () 处得到一个错误点
    【解决方案3】:

    ECMAScript6 及以上版本中,您可以通过exportimport 关键字来实现。

    首先,在一个单独的js文件中实现和export一个箭头函数:

    //file1.js
    export const myFunc = () => {
        console.log("you are in myFunc now");
    }
    

    然后,import 并在其他文件中调用它:

    //otherfile.js
    
    import { myFunc } from 'file1';
    
    myFunc();
    

    If you want to more about Arrow functions

    【讨论】:

    • 应该注意你需要一个编译器。它不仅仅是“工作”。
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多