Nar*_*esh 114 javascript commonjs node.js
根据Node.js手册:
如果希望模块导出的根是函数(例如构造函数),或者如果要在一个赋值中导出完整对象而不是一次构建一个属性,请将其分配给module.exports而不是export .
给出的例子是:
// file: square.js
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用:
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());
Run Code Online (Sandbox Code Playgroud)
我的问题:为什么示例不使用square作为对象?以下是否有效,是否使示例更"面向对象"?
var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());
Run Code Online (Sandbox Code Playgroud)
Suk*_*ima 168
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);
Run Code Online (Sandbox Code Playgroud)
在上面的例子中module.exports,exports它们是同一个对象.很酷的部分是你在CommonJS模块中看不到任何这些,因为整个系统都会为你解决这个问题,你需要知道的是有一个带有exports属性的模块对象和一个指向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"
Run Code Online (Sandbox Code Playgroud)
对于非构造函数的函数也是如此:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
Run Code Online (Sandbox Code Playgroud)
mač*_*ček 127
在我看来,一些node.js的例子非常人为.
你可能希望在现实世界中看到更像这样的东西
// square.js
function Square(width) {
if (!(this instanceof Square)) {
return new Square(width);
}
this.width = width;
};
Square.prototype.area = function area() {
return Math.pow(this.width, 2);
};
module.exports = Square;
Run Code Online (Sandbox Code Playgroud)
用法
var Square = require("./square");
// you can use `new` keyword
var s = new Square(5);
s.area(); // 25
// or you can skip it!
var s2 = Square(10);
s2.area(); // 100
Run Code Online (Sandbox Code Playgroud)
对于ES6人
class Square {
constructor(width) {
this.width = width;
}
area() {
return Math.pow(this.width, 2);
}
}
export default Square;
Run Code Online (Sandbox Code Playgroud)
在ES6中使用它
import Square from "./square";
// ...
Run Code Online (Sandbox Code Playgroud)
使用类时,必须使用new关键字对其进行实例化.其他一切都保持不变.
| 归档时间: |
|
| 查看次数: |
114039 次 |
| 最近记录: |