Javascript模块:原型与导出

ell*_*111 10 javascript prototype module node.js

我是node.js(和stackoverflow)的新手,并没有找到对此的确切解释.

这可能是一个试验性的答案,但希望它能帮助那些也从Python /其他面向对象框架过渡的人.

我已经看过其他关于原型概念在js中的文章,还有其他文章解释了node.js的module.exports.

我正在研究Ghost CMS,他们同时使用它们.我似乎无法找出为什么他们会在某些情况下选择一个而不是另一个.

任何帮助都表示赞赏,即使它指向其他链接.

vku*_*kin 13

实际上它们是可以互换的(在某种程度上):

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();
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

不过,第一个例子对于javascript来说更具惯用性.

  • 它们根本不是可以互换的.与对象的原型接口并与(模块)对象的导出属性连接具有非常不同的典型用例.它充其量是误导性的,并且认为它们可以互换可能是有害的.JS开发人员应该真正理解其中的差异 (2认同)

pra*_*tsj 6

使用node.js,module.exports是一个公开模块的公共接口的方式.

/* my-module.js */

exports.coolFunction = function(callback) {

    // stuff & things
    callback(whatever);
};
Run Code Online (Sandbox Code Playgroud)

在导入/要求之后,该接口可以由另一个模块使用:

/* another-module.js */

var myModule = require('my-module');

myModule.coolFunction(function(error) { ... });
Run Code Online (Sandbox Code Playgroud)

另一方面,原型(简单的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();
Run Code Online (Sandbox Code Playgroud)

干杯.