dynamic添加属性到节点模块

我正在尝试不同的方式来编写一个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 }; 

游戏test.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); }); ... 

我得到的错误"Cannot read property 'board' of undefined"

如果我删除.initialize()我得到一个游戏的实例,但没有属性。 我不确定这是否是一个好的模式,但首先想知道我在这里做错了什么。 然后,我有任何额外的build议,我打开听证会。

Game.initialize是一个函数。

在你的testing中你没有调用函数,所以你的variablesnewGame只是一个Game.initialize的引用,而不是一个Game实例

 // your line newGame = new game().initialize; // should be newGame = new game().initialize(); 

编辑:另外,你可能想在你的initialize()函数中使用this而不是game