是否可以访问同一文件中的其他模块导出功能

Is it possible to access other module export functions within the same file?

本文关键字:其他 模块 功能 文件 访问 是否      更新时间:2023-09-26

我在同一个文件中有两个函数,都是从外部访问的。其中一个函数由第二个函数调用。

module.exports.functionOne = function(param) {
    console.log('hello'+param);
};
module.exports.functionTwo = function() {
    var name = 'Foo';
    functionOne(name);
};

执行此命令时,对 functionOne 的调用被标记为未定义。

引用它的正确方法是什么?

我发现一种有效的模式是引用文件本身。

var me = require('./thisfile.js');
me.functionOne(name);

。但感觉必须有更好的方法。

只是简单地module.exports.functionOne() .

如果这太麻烦,只需执行以下操作:

function fnOne() {
    console.log("One!");
}
module.exports.fnOne = fnOne;
var me = require(module.filename);
me.functionOne(name);

或者只使用导出对象本身

module.exports.functionOne(name);

我想我一直在考虑 require 等同于包含、导入等。 如果有另一种解决方法,看到它可能会很有趣。 我耳朵后面还是湿漉漉的。

James Herdmans Understanding Node.js"require"帖子在帮助代码组织方面确实帮助了我。 绝对值得一看!

// ./models/customer.js
Customer = function(name) {
  var self = this;
  self.name = name;
};
// ./controllers/customercontroller.js
require("../models/customer");
CustomerController = function() {
  var self = this;
  var _customers = [
   new Customer("Sid"),
   new Customer("Nancy")
  ];
  self.get() {
   return _customers;
  }
};