gpt4 book ai didi

javascript - node.js 中模块模式的最佳实践

转载 作者:行者123 更新时间:2023-11-30 08:40:09 32 4
gpt4 key购买 nike

我一直在转换一些旧的 javascript 以便在 node.js 模块中使用,这让我开始思考模块模式选项。

我见过许多使用导出的结构。 module.exports 甚至原型(prototype),这让我想知道哪种方法被认为是最佳实践,为什么?

这是我用两种方式编写的代码中的一个精简模块示例。

选项 1:

var Helper = function() {};
Helper.latin_map = {"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A"};

Helper.prototype.urlise = function(orgString){
var lower = orgString.toLowerCase();

var latinised = lower.replace(/[^A-Za-z0-9\[\] ]/g, function(a) {
return Helper.latin_map[a] || a;
});

return latinised.replace(/\s+/g, '-')
}

module.exports = new Helper();

选项 2:

var latin_map = {"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A"};

module.exports = {
urlise : function(orgString){
var lower = orgString.toLowerCase();
var latinised = lower.replace(/[^A-Za-z0-9\[\] ]/g, function(a) {
return latin_map[a] || a;
});

return latinised.replace(/\s+/g, '-')
}
}

这是一个非常简单的示例,但我将对其进行扩展以在同一模块中提供多个可访问的功能,因此在我允许事情变得过于复杂之前。我想我会就哪种方法被认为是最佳实践寻求一些建议。

最佳答案

I have seen a number of structures using exports, module.exports and even prototype, and it has left me wondering which method is considered best practice and why?

具有.prototype 的东西是构造函数,模块将它们导出为要实例化的

当您想导出具有静态属性的“单例”对象时,可以使用导出普通对象(通常作为文字)甚至扩展默认为空的 exports 对象,因此说。

 module.exports = new Helper()

This is almost always wrong . Helper 是完全不必要的,通常甚至是令人反感的。

您应该选择选项 2。如果您确实只导出了一个函数,您可能会考虑 module.exports = function urlise(orgString){...},但要导出多个可访问的函数您的选项 2 的模块正是要使用的模式。

关于javascript - node.js 中模块模式的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370124/

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