简体   繁体   English

node.js模块-将对象及其属性导出为函数

[英]node.js modules - exporting both the object and it's properties as functions

I'd like to have a module which exports functions like this: 我希望有一个模块可以导出如下功能:

var log = require("log.js");
log("hello");       // should run console.log("hello")
log.info("world");  // should run console.log("world")

What would the contents of log.js be to achieve this? 为了实现这一目标,log.js的内容是什么? I've tried tampering with the module.exports object but can't seem to achieve this functionality. 我试图篡改module.exports对象,但似乎无法实现此功能。

function logger (data) {
    console.log(data);
}

logger.info = function (data) {
    console.log(data);
}

exports = module.exports = logger;

Instead of writing the same function again, you can also do 除了再次编写相同的功能,您还可以

logger.info = logger;

If you are interested to know more about module.exports and exports , read this blog entry of mine. 如果您想了解有关module.exportsexports更多信息,请阅读我的博客条目。

exports.log = function(msg) { 
    console.log(msg);
}
exports.info = function(msg) {
    console.log(msg);
}

Another way of doing it. 另一种方式。

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

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