从另一个类nodejs获取新对象

时间:2016-04-26 17:36:24

标签: node.js

好的,我有一个包含

的课程

对象JS

var GameServer = require("./GameServer");
var gameServer = new GameServer();

GameServer()包含

GameServer JS

function GameServer() {
    // Startup
    this.run = true;
    this.lastNodeId = 1;
    this.lastPlayerId = 1;
    this.clients = [];
    this.largestClient; // Required for spectators
    this.nodes = [];
    this.nodesVirus = []; // Virus nodes
    this.nodesEjected = []; // Ejected mass nodes
    this.nodesPlayer = []; // Nodes controlled by players
}

现在,我试图实现的是从ObjectClass

获取gameServer

在我的课堂上我试过

新JS

var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;

但是从这个方面来说,我无法获得类GameServer()属性。我是节点的新手,对不起,我不得不问这个问题。我现在卡住了

当我尝试从GameServer中获取客户端时

var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
gameServer.clients.length;

我收到错误,客户端未定义。有什么方法吗?。

我无法修改GameServer或Object js。。基本上我将脚本设置为脚本以获得额外的功能。

1 个答案:

答案 0 :(得分:1)

您缺少文件的导出,因此在执行require(文件)时,您将获取并清空对象{} ..

对于gameServer,您应该执行以下操作:

'use strict';
function GameServer() {
    // Startup
    this.run = true;
    this.lastNodeId = 1;
    this.lastPlayerId = 1;
    this.clients = [];
    this.largestClient; // Required for spectators
    this.nodes = [];
    this.nodesVirus = []; // Virus nodes
    this.nodesEjected = []; // Ejected mass nodes
    this.nodesPlayer = []; // Nodes controlled by players
}

module.exports =  exports = GameServer;

对象类

'use strict';
var GameServer = require("./GameServer");
var gameServer = new GameServer();
exports.gameServer = gameServer;

您需要了解需要缓存文件返回的值,因此您将使用gameServer的单例。