簡體   English   中英

動態向節點模塊添加屬性

[英]Adding properties dynamically to node module

我正在嘗試不同的方式來編碼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
    };

game-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(),則會得到游戲實例,但沒有屬性。 我不確定這是否是一個好的模式,但首先想知道我在這里做錯了什么。 然后還有其他建議可供我聽取。

Game.initialize是一個函數。

在測試中,您沒有調用函數,因此變量newGame只是對Game.initialize的引用,而不是Game實例

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

編輯:此外,您可能想在initialize()函數中使用this而不是game

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM