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

时间:2015-12-14 19:42:30

标签: 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(" ");
&#13;
&#13;
&#13;

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

&#13;
&#13;
// ================== 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
};
&#13;
&#13;
&#13;

&#13;
&#13;
// ============= 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' }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

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

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有用。