简体   繁体   English

this.prototype和module.exports之间的区别?

[英]Differences between this.prototype and module.exports?

As I am new to Node.js I am looking for some info, coding some testing stuff and also reading some other people's code. 由于我是Node.js新手,我正在寻找一些信息,编写一些测试内容并阅读其他人的代码。

I've seen that creating/requiring(using) modules is typical in Node.js . 我已经看到创建/需要(使用)模块在Node.js是典型的。 I've seen different ways of defining "public" methods and function inside modules and both seem to work the same way too: 我已经看到了在模块中定义“公共”方法和函数的不同方法,两者似乎也以同样的方式工作:

  • module.exports
  • this.prototype

Is there a notable difference by using one or another? 使用一个或另一个有明显的区别吗? Or are just different ways of doing the same thing? 或者只是做同样事情的不同方式? Is any of these two better, or it depends on the context? 这两个中的任何一个更好,还是取决于具体情况?

You should use either exports to attach properties to the predefined exported object or reassign module.exports to your own object. 您应该使用exports将属性附加到预定义的导出对象,或者将module.exports重新分配给您自己的对象。 The latter is common when exporting a constructor for example. 例如,在导出构造函数时,后者很常见。

exports.foo = function() { console.log('Hello world!'); };
exports.add = function(a, b) { return a + b; };

// Then the module might be used like so:
// var mymodule = require('./mymodule');
// mymodule.foo();
// console.log(mymodule.add(1, 9));

Or replace the exports object: 或者替换exports对象:

function Foo() {

}

module.exports = Foo;

// then typically users do this in their script:
// var Foo = require('./mymodule');
// var myFoo = new Foo();

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

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