Prototype methods not found in a NodeJS session

I am trying to learn Javascript and NodeJS by creating a small game and I am having a problem. When I attach an object to a session, whenever I reprocess this session, I no longer have access to any prototype methods that I define on it.

In one file with the name 24.jsI have

function Deck() {
    this.cards = [];
    for (var i = 0; i < 52; i++) {
        this.cards[i] = Math.floor(i / 4) + 1;
    }
    this.done = false;
}

function GameState() {
    // holds game state and game logic
    this.time = 0;
    this.score = 0;
    this.deck = new Deck();
    this.deck.deal();
}
Deck.prototype.deal = function() {
    // not that important
}

var gameMaker = exports = module.exports = function() {
    return new GameState();
}

Then in my main file I have

var express = require('express');
var gameMaker = require('./24.js');

var app = express();
app.use(express.static(__dirname + '/static'));
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({
    secret: 'supersecret',
    key: 'express.sid'
}));

app.get('/', function (req, res) {
    if (!req.session.game) {
        req.session.game = gameMaker();
    }
    var game = req.session.game;
    // Access data from game to send to client
});

app.post('/verify', function (req, res) {
    // assumes game exists, check for this later
    var game = req.session.game;
    game.score += 1;
    game.deck.deal();
    res.redirect("/");
});

I get an error when I do a POST because it says Object #<Object> has no method 'deal'. I checked, and I can still call the method the deal()first time the page loads, and I can also access other information (for example, the score of the game or which maps were the last). The only thing that breaks down is that the method calls the same session.

+4
1

, , , JSON.stringify(req.session). , JS, , Deck.prototype, JSON.

. , / , .

+4

Source: https://habr.com/ru/post/1530373/


All Articles