CommonJS模块的模式? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我一直在有趣的“升级你的编码”网站上进行一些练习,Exercism.io他们使用CommonJS样式模块进行代码示例和使用Jasmine进行测试。我一直认为模块是我不想处理的麻烦,但在这些一口大小的块中,看起来它们在我的单页应用程序中开始使用会非常有用。所以我一直在谷歌搜索并搜索Github以获得使用CommonJS模块的一些好样本 - 但仍然没有找到一个详细解释主要模式是什么,以及它们如何不同的样本。例如,我提交的一个答案看起来像这样:

var HelloWorld = function () {};

HelloWorld.prototype.hello = function () {
  return 'Hello, World!'
};

module.exports = HelloWorld;

但另一个看起来像这样

var Bob = function () {
    this.hey = function (input) {
        input = input.split('');
        if (input.indexOf('!') >= 0) {return 'Whoa, chill out!'}
        if (input.indexOf('?') >= 0) {return 'Sure.'}           
        return 'Whatever.'
    };

}

module.exports = Bob;

具体来说,我想知道在父定义中嵌套一个函数与Bob hey()函数之间的区别是什么,而不是HelloWorld hello()使用原型的方式。

javascript node-modules commonjs
1个回答
2
投票

从作为示例给出的两个函数开始,它们彼此完全不同,并且具有不同的用途。

根据您所拥有的代码,您调用它们的方式也是不正确的。

对于您的Bob示例,您所做的只是为变量分配函数。为了打电话,你只需要做Bob()。如果你做一个Bob.hello()你会得到一个错误。

另一方面,HelloWorld不仅仅是一个函数,嗯..因为你宣称它是一个空函数,如果你做HelloWorld()就会调用它。但是你定义了hello作为它的原型函数,你可以直接调用它来执行HelloWorld.prototype.hello()。我估计这些主要用于改变现有对象或函数的行为。

您在问什么是编写模块的最有效方法,但实际上并没有正确的答案。所有模块都是一段代码,可以被其他文件导出和重用。无论你喜欢什么,它们都可以是函数,对象,简单变量!

所以基本上你可以做所有这些:

// moduleThatExportsANumber.js
module.exports = 1

// moduleThatExportsAnObject.js
module.exports = {}

// moduleThatExportsAFunction.js
module.exports = function () { return 'say somethign!'}

// main.js Lets call all the modules!
const number = require('./moduleThatExportsANumber)
const object = require('./moduleThatExportsAnObject)
const function = require('./moduleThatExportsAFunction)

console.log(number) // 1
console.log(object) // {}
console.log(function) // function () { return 'say somethign!'}
console.log(function()) //say somethign!

模块的全部内容就是简单地在文件中编写内容,导出那些东西,在CommonJS的情况下通过module.exports = [whatever you are exporting]完成,然后导入,这对于CommonJS来说是require('./filename')

现在......回到原来的问题,你的备忘单。不幸的是我不知道任何CommonJS,但是here是关于CommonJS模块系统的一篇不错的博客文章,here也是一个你喜欢的JavaScript版本。

© www.soinside.com 2019 - 2024. All rights reserved.