javascript - 如何使用 Exports 或 module.exports 将带有原型(prototype)的函数构造函数对象方法包装在单个模块中

标签 javascript node.js

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

function Vector(x, y) {
  this.x = x;
  this.y = y;
}
Vector.prototype.plus = function(other) {
  return new Vector(this.x + other.x, this.y + other.y);
};

function Grid(width, height) {
  this.space = new Array(width * height);
  this.width = width;
  this.height = height;
}
Grid.prototype.isInside = function(vector) {
  return vector.x >= 0 && vector.x < this.width &&
         vector.y >= 0 && vector.y < this.height;
};
Grid.prototype.get = function(vector) {
  return this.space[vector.x + this.width * vector.y];
};
Grid.prototype.set = function(vector, value) {
  this.space[vector.x + this.width * vector.y] = value;
};

var directions = {
  "n":  new Vector( 0, -1),
  "ne": new Vector( 1, -1),
  "e":  new Vector( 1,  0),
  "se": new Vector( 1,  1),
  "s":  new Vector( 0,  1),
  "sw": new Vector(-1,  1),
  "w":  new Vector(-1,  0),
  "nw": new Vector(-1, -1)
};

function randomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

var directionNames = "n ne e se s sw w nw".split(" ");

回答后编辑:我根据 Alexander M 做了一个更简单的例子

// ================== lib.js

function User(n, p) {
	this.n = n;
	this.p = p;
}

User.prototype.user = function() {
	console.log("user: " + this.n + ", pass: " + this.p);
};

function Client(n, p, m) {
	User.call(this, n, p);
	this.m = m;
}

Client.prototype = new User();

Client.prototype.full = function() {
	console.log(this.m);
};

module.exports = 
{
	User,
	Client
};

// ============= FILE.JS

var mod = require('./lib.js');

var john = new mod.Client("john", "mskjqh", "john@gmail.com");

john.user();
john.full();
console.log(john);

// input
// user: john, pass: mskjqh
// john@gmail.com
// User { n: 'john', p: 'mskjqh', m: 'john@gmail.com' }

最佳答案

据我了解,您想导出所有内容,对吧?

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;

您可能还会发现this question有用。

关于javascript - 如何使用 Exports 或 module.exports 将带有原型(prototype)的函数构造函数对象方法包装在单个模块中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275286/

相关文章:

node.js - 当 find 查询为空时,mongoose 会返回什么?

javascript - 添加带有 "save"或 "no"的警告框

javascript - 在html中加载脚本序列

javascript - 如何防止同一用户使用 Firebase 同时登录?

javascript - 如何让按键在输入字段上不起作用

javascript - 在评估方法之外处理来自 puppeteer 页面上下文的事件

javascript - mailchimp 使用 Node js 服务器取消订阅

node.js - req.params.id 未定义,我不明白为什么

javascript - 具有响应和 http 方法的 Node JS 变量范围

javascript - 以编程方式启动 vue-cli-service serve 时控制 webpack 的冗长程度