我正在尝试用不同的方式来编写 Node.js 模块并试过这个:
game.js
var board = require('./board'),
player = require('./player');
// setting module.exports to a function constructor so I can make instances of this node module from my test
var game = module.exports = function(){};
// dynamically add properties and set their default values
// I don't think I need to use any prototypes here right?
// And yes I realize I could use ES6 classes with an explicit constructor but that's a suggestion we can put on the side for now...
game.initialize = function(){
game.started = false;
game.status = 'not started';
game.board = board.create();
return game;
};
game.start = function(){
game.started = true
};
游戏测试.js
let chai = require('chai'),
should = chai.should(),
game = require('../src/game');
describe('Game - Initial State', () => {
var newGame;
beforeEach((done) => {
newGame = new game().initialize;
done();
});
it('should contain a new board to play on', () => {
should.exist(newGame.board);
});
...
我收到错误 “无法读取未定义的属性‘board’”
如果我删除 .initialize() 我得到一个游戏实例,但没有属性。我不确定这是否是一个好的模式,但首先想知道我在这里做错了什么。然后是我愿意听取的任何其他建议。
最佳答案
Game.initialize
是一个函数。
在您的测试中,您没有调用该函数,因此您的变量 newGame
只是对 Game.initialize
的引用,而不是 Game
实例
// your line
newGame = new game().initialize;
// should be
newGame = new game().initialize();
编辑:此外,您可能希望在 initialize()
函数中使用 this
而不是 game
.
关于javascript - 动态添加属性到 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33995555/