【问题标题】:const foo = module.exports = yadablah(){}; Why the const foo before module.exports?const foo = module.exports = yadablah(){};为什么在 module.exports 之前有 const foo?
【发布时间】:2017-11-09 22:34:44
【问题描述】:

我将 module.exports 的概念理解为一个容器对象,具有属性导出,需要时返回。

但是这里“const foo =”的目的是什么?

编辑:

(模块用户.js)

const User = module.exports = mongoose.model('User', userSchema);
module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}

好的。现在我输入了上下文,这是有道理的。我最初将“User.findById”误读为不同的 var (const)。太尴尬了!

【问题讨论】:

  • 看不到太多(如果有的话)用例。你能分享一个更详细的例子吗?
  • @Daniel 我进行了编辑。太尴尬了!
  • 写的很糟糕。将其写为:const User = mongoose.model(...); User.getUserById = function (){...}; module.exports = User; 会更易读,不会损失任何性能,而且它只需要 一个 额外的行。

标签: javascript node.js


【解决方案1】:

这是模块的样子:

var module = { 
      exports: {
         yadablah: function(){
           //code
         }
} };

foomodule.exports 在这里都引用同一个对象,即函数

yadablah()

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多