javascript - 动态添加属性到 Node 模块

标签 javascript node.js

我正在尝试用不同的方式来编写 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/

相关文章:

javascript - Getter/Setter 和原型(prototype)链

javascript - 嵌套的纯函数还是纯函数吗?

javascript - 如何根据另一个下拉值选择多选动态填充的下拉列表

performance - Apache 后面的 node.js 是否比 node.js HTTP 服务器慢得多?

javascript - AJAX:动态更改第二页的内容

javascript - Express 路由器无法识别 Mongoose 模型

macos - 在哪里放置 node.js 安装的 Node 文件夹?

node.js - 如何获取 schema.pre() 方法中的特定字段?

javascript - 使用 NodeJS 提供内容,但响应类型始终为 ""

javascript - 如何设置一个专注于点击的元素?