Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用exports或module.exports将函数构造函数对象方法与原型包装在单个模块中_Javascript_Node.js - Fatal编程技术网

Javascript 如何使用exports或module.exports将函数构造函数对象方法与原型包装在单个模块中

Javascript 如何使用exports或module.exports将函数构造函数对象方法与原型包装在单个模块中,javascript,node.js,Javascript,Node.js,我想用这段代码创建一个“网格”模块,我尝试了使用exports或module.exports在其他文件中使用它的不同方法,但没有成功。我想要一个require('./grid.js'),并在其他文件中使用这个对象和函数 函数向量(x,y){ 这个.x=x; 这个。y=y; } Vector.prototype.plus=函数(其他){ 返回新向量(this.x+other.x,this.y+other.y); }; 功能网格(宽度、高度){ this.space=新数组(宽度*高度); 这个。

我想用这段代码创建一个“网格”模块,我尝试了使用exports或module.exports在其他文件中使用它的不同方法,但没有成功。我想要一个require('./grid.js'),并在其他文件中使用这个对象和函数

函数向量(x,y){ 这个.x=x; 这个。y=y; } Vector.prototype.plus=函数(其他){ 返回新向量(this.x+other.x,this.y+other.y); }; 功能网格(宽度、高度){ this.space=新数组(宽度*高度); 这个。宽度=宽度; 高度=高度; } Grid.prototype.isInside=函数(向量){ 返回vector.x>=0&&vector.x=0&&vector.yvar directionNames=“东北东南西南西北”。拆分(“”)据我所知,您想导出所有内容,对吗

function Vector(x, y) {
  ...
}

function Grid(width, height){
  ...
}

module.exports = {
  Vector: Vector,
  Grid : Grid,
  directionNames : directionNames,
  ...
};
如果您使用的是node.js 4+,则可以使用简短的ES6语法:

module.exports = {
  Vector,
  Grid,
  directionNames,
  ...
};
然后,在另一个文件中,您将

var Vector = require('./path/to/grid.js').Vector;

你可能也会发现这很有用

var grid = require('./path/to/grid.js');
var Vector = grid.Vector;