Javascript 模块:原型与导出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21939568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:03:25  来源:igfitidea点击:

Javascript Modules: Prototype vs. Export

javascriptnode.jsmoduleprototype

提问by elloworld111

I'm new to node.js (and stackoverflow) and haven't found an exact explanation of this.

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

This is probably a trial answer but hopefully it'll help someone else who's also transitioning from Python/other object oriented frameworks.

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

I've seen other articles about what the prototype concept is in js and then others that explain the module.exports of node.js.

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

I'm studying the Ghost CMS and they use both. I can't seem to pick out why they would choose one over the other in certain cases.

我正在研究 Ghost CMS,他们两者都使用。我似乎无法弄清楚为什么在某些情况下他们会选择一个而不是另一个。

Any help is appreciated, even if it's pointing me to other links.

感谢任何帮助,即使它指向我其他链接。

采纳答案by prattsj

With node.js, module.exportsis how one exposes the public interface of a module.

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

/* my-module.js */

exports.coolFunction = function(callback) {

    // stuff & things
    callback(whatever);
};

This interface can then be consumed by another module after importing/requiring it:

在导入/需要它之后,这个接口可以被另一个模块使用:

/* another-module.js */

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

myModule.coolFunction(function(error) { ... });

Prototypes(a plain Javascript feature), on the other hand, are useful for defining shared properties and methods of objects instantiated from a constructor function.

另一方面,原型(一种简单的 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();

Cheers.

干杯。

回答by vkurchatkin

Actually they are interchangeable (in a way):

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

with prototype:

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();

with exports:

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();

The first example is more idiomatic for javascript, though.

不过,第一个示例更适合 javascript。