假设我想公开一个名为 Print
的方法
- 作为
原型(prototype)
的绑定(bind)方法:
文件另存为 Printer.js
var printerObj = function(isPrinted) {
this.printed = isPrinted;
}
printerObj.prototype.printNow = function(printData) {
console.log('= Print Started =');
};
module.exports = printerObj;
然后通过将代码 require('Printer.js').printNow()
放入任何外部 .js Node 程序文件中来访问 printNow()
。
- 使用
module.exports
导出方法本身:
文件另存为 Printer2.js
var printed = false;
function printNow() {
console.log('= Print Started =');
}
module.exports.printNow = printNow;
然后通过将代码 require('Printer2.js').printNow()
放入任何外部 .js Node 程序文件中来访问 printNow()
。
谁能说出它与 Node.js 的区别和最佳实现方式是什么?
最佳答案
当然是第一种方式。它被称为 substack pattern
,您可以在 Twitter 上阅读它。以及 Mikeal Rogers 的 blog .一些代码示例可以在 jade github repo 中找到。在解析器中:
var Parser = exports = module.exports = function Parser(str, filename, options){
this.input = str;
this.lexer = new Lexer(str, options);
...
};
Parser.prototype = {
context: function(parser){
if (parser) {
this.contexts.push(parser);
} else {
return this.contexts.pop();
}
},
advance: function(){
return this.lexer.advance();
}
};
关于node.js - 从 Node.js 公开方法的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516717/