gpt4 book ai didi

javascript - 讲require、import、packages的node-way是什么?

转载 作者:行者123 更新时间:2023-11-30 15:56:10 25 4
gpt4 key购买 nike

我的 javascript 项目中有两个文件:

应用程序.js

require('sugar')
var Notification = require('./notification');

let createdOn = 'now'
let notifyOn = 'in 2 days'
let someNotification = new Notification('go somewhere', Date.create(createdOn), Date.create(notifyOn))
someNotification.print()

通知.js

function Notification(content, createdOn, notifyOn) {
this.content = content
this.createdOn = createdOn
this.notifyOn = notifyOn
}

Notification.prototype.print = function() {
console.log('content', this.content)
console.log('createdOn', this.createdOn)
console.log('notifyOn', this.notifyOn)
}

module.exports = Notification

notification.js 中,我想我是在“编写我自己的模块”,它“导出一个构造函数”到任何需要它的地方。然后在 app.js 中,我“导入通知模块”,它与 app.js 位于同一工作目录中。我还“导入了 Sugar 包”,因此我可以将自然语言转换为 DateTime 参见 Sugar.js有关详细信息。

接下来我要“创建一个 Notification 实例”并调用其中一个“实例方法”。

我想知道:上面所有内容的 Node 方式是什么,尤其是引号中的部分?具体来说,我对如何准确地谈论构造函数和原型(prototype)函数以及这两行之间的区别感到困惑:

require('sugar')
var Notification = require('./notification');

我正在寻找一个答案,它使用 Node 习语向我解释了我在我的项目中所做的事情。

谢谢😄

最佳答案

没有记录在案的标准 Node 惯用语。您的解释几乎是您在任何 Node 开发人员都能理解的方面所做的事情。这是我能想到的最短的 Node 短语:

require('sugar')

加载糖模块

var Notification = require('./notification');

从当前模块的目录加载通知模块并将导出分配给名为Notification的变量

notification.js

导出用于创建Notification 对象的构造函数的模块。


what the difference is between these two lines:

require('sugar')
var Notification = require('./notification');

可以在不将其导出分配给任何变量的情况下使用 sugar 模块,因为它所做的主要事情是将方法添加到现有的 DateNumber 原型(prototype)(通常称为作为“扩展现有对象”),您可以通过访问它添加的 Date.create() 等方法来使用它的许多功能。

因此,它的功能被添加到已经存在的对象中,这就是您使用它的功能的方式。这不是特别常见 - 我不知道以这种方式加载的模块的任何特定名称。

Next I'm "creating an instance of Notification" and calling one of its "instance methods".

这已经是一种 Node 方式了。

关于javascript - 讲require、import、packages的node-way是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38492590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com