gpt4 book ai didi

javascript - Node.js - 使用 module.exports 作为构造函数

转载 作者:IT老高 更新时间:2023-10-28 21:47:13 27 4
gpt4 key购买 nike

根据 Node.js 手册:

If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.

给出的例子是:

// file: square.js
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}

并像这样使用:

var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

我的问题:为什么示例不使用正方形作为对象?以下内容是否有效,是否使示例更加“面向对象”?

var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());

最佳答案

CommonJS 模块允许两种方式来定义导出的属性。无论哪种情况,您都返回一个对象/函数。因为函数是 JavaScript 中的一等公民,所以它们可以像对象一样工作(从技术上讲,它们是对象)。也就是说,您关于使用 new 关键字的问题有一个简单的答案:是的。我来说明...

模块导出

您可以使用提供的 exports 变量将属性附加到它。一旦在另一个模块中需要,这些分配属性就会变得可用。或者,您可以将对象分配给 module.exports 属性。在任何一种情况下,require() 返回的都是对 module.exports 值的引用。

如何定义模块的伪代码示例:

var theModule = {
exports: {}
};

(function(module, exports, require) {

// Your module code goes here

})(theModule, theModule.exports, theRequireFunction);

在上面的示例中,module.exportsexports 是同一个对象。很酷的部分是您在 CommonJS 模块中看不到任何这些,因为整个系统会为您处理所有您需要知道的是有一个具有导出属性的模块对象和一个指向与 module.exports 相同。

需要构造函数

由于您可以将函数直接附加到 module.exports,因此您实际上可以返回一个函数,并且像任何函数一样,它可以作为 构造函数 进行管理(斜体字从JavaScript 中函数和构造函数之间的唯一区别是您打算如何使用它。从技术上讲,没有区别。)

所以以下是非常好的代码,我个人鼓励它:

// My module
function MyObject(bar) {
this.bar = bar;
}

MyObject.prototype.foo = function foo() {
console.log(this.bar);
};

module.exports = MyObject;

// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"

非构造函数需要

类似非构造函数的函数也是如此:

// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}

// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"

关于javascript - Node.js - 使用 module.exports 作为构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534702/

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