Javascript模块:原型与导出

我是新的node.js(和stackoverflow),并没有find一个确切的解释。

这可能是一个试用的答案,但希望它可以帮助别人也从Python /其他面向对象的框架转换。

我见过其他文章,关于js中的原型概念是什么,然后是其他解释node.js的module.exports的其他文章。

我正在研究Ghost CMS,他们都使用这两个。 我似乎无法找出为什么他们会在某些情况下select一个。

任何帮助表示赞赏,即使它指向我的其他链接。

使用node.js, module.exports是如何暴露模块的公共接口。

 /* my-module.js */ exports.coolFunction = function(callback) { // stuff & things callback(whatever); }; 

这个接口可以被其他模块在导入/需要之后使用:

 /* another-module.js */ var myModule = require('my-module'); myModule.coolFunction(function(error) { ... }); 

另一方面, 原型 (一个简单的Javascript特性)对定义从构造函数实例化的对象的共享属性和方法很有用。

 function User() { this.name = null; } User.prototype.printGreeting = function() { console.log('Hello. My name is: ' + this.name); }; var user = new User(); user.name = 'Jill'; user.printGreeting(); 

干杯。

其实它们是可以互换的(以某种方式):

prototype

 //module.js function Person (name) { this.name = name; } Person.prototype.sayName = function () { console.log(this.name); } module.exports = Person; //index.js var Person = require('./module.js'); var person = new Person('John'); person.sayName(); 

exports

 //module.js exports.init = function (name) { this.name = name; return this; } exports.sayName = function () { console.log(this.name); } //index.js var Person = require('./module.js'); var person = Object.create(Person).init('John'); person.sayName(); 

不过,第一个例子对于JavaScript来说更具惯用。