从module.exports中的另一个函数调用module.exports中的“local”函数?

本文翻译自:Call a “local” function within module.exports from another function in module.exports?

How do you call a function from within another function in a module.exports declaration? 如何从module.exports声明中的另一个函数中调用函数?

Here's some simplified code. 这是一些简化的代码。

In my app.js, I do the following: 在我的app.js中,我执行以下操作:

var bla = require('./bla.js');
console.log(bla.bar());

and inside of bla.js is 而在bla.js里面是

module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    this.foo();
  }

}

I'm trying to access the function foo from within the function bar , and I'm getting: 我正试图从功能bar访问函数foo ,我得到:

TypeError: Object # has no method 'foo'

If I change this.foo() to just foo() I get: 如果我将this.foo()更改为foo()我得到:

ReferenceError: foo is not defined


#1楼

参考:https://stackoom.com/question/hthX/从module-exports中的另一个函数调用module-exports中的-local-函数


#2楼

I think I got it. 我想我明白了。 I just changed this.foo() to module.exports.foo() and it seems to be working. 我刚刚将this.foo()更改为module.exports.foo() ,它似乎正在工作。

If someone has a better or more proper method, please feel free to correct me. 如果某人有更好或更正确的方法,请随时纠正我。


#3楼

You could declare your functions outside of the module.exports block. 您可以在module.exports块之外声明您的函数。

var foo = function (req, res, next) {
  return ('foo');
}

var bar = function (req, res, next) {
  return foo();
}

Then: 然后:

module.exports = {
  foo: foo,
  bar: bar
}

#4楼

You can also save a reference to module's global scope outside the (module.)exports.somemodule definition: 您还可以在(module。)exports.somemodule定义之外保存对模块全局范围的引用:

var _this = this;

exports.somefunction = function() {
   console.log('hello');
}

exports.someotherfunction = function() {
   _this.somefunction();
}

#5楼

Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. 另一个选项,更接近OP的原始样式,是将要导出的对象放入变量并引用该变量以调用对象中的其他方法。 You can then export that variable and you're good to go. 然后你可以导出那个变量,你就可以了。

var self = {
  foo: function (req, res, next) {
    return ('foo');
  },
  bar: function (req, res, next) {
    return self.foo();
  }
};
module.exports = self;

#6楼

You can also do this to make it more concise and readable. 您也可以这样做,使其更简洁和可读。 This is what I've seen done in several of the well written open sourced modules: 这是我在几个编写良好的开源模块中看到的:

var self = module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    self.foo();
  }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值