如何使用exports或module.exports将函数构造函数对象方法与原型封装在单个模块中
how would you wrap function constructor object method with prototype in a single module using exports or module.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.js4+,你可以使用简短的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;
你可能也会发现这个问题很有用。
相关文章:
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 为什么要对define.md和module.exports进行条件检查,以及条件何时通过
- 在gump和nodejs中使用Typescript时,未定义对require和exports的引用
- AngularJS中的封装窗口全局变量
- 闭包如何具体化数据封装
- 使用解析为javascript源的.php,如何使用条件语句将javascript代码封装在php括号之间
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 电子构建器与电子封装器
- 将两个express应用程序封装在一个应用程序中
- 试图封装$.getJSON和RequireJS
- 在JSX中围绕React组件封装高阶组件(HOC)
- 以最封装的方式封装/封装ScalaJS react js组件(react stick)
- 在jasmine规范中使用module.exports
- JS在封装对象中查找键值对
- React.js错误;相邻的JSX元素必须被封装在一个封闭标记“中;
- 如何在多个控制器之间封装设置$scope值
- js添加封装来修改属性值
- 将JS封装到GWT单元格表中
- 我们可以在一个js文件中有多个module.exports语句吗
- 如何使用exports或module.exports将函数构造函数对象方法与原型封装在单个模块中