简体   繁体   English

Node.js和面向对象的Javascript

[英]Node.js and Object Oriented Javascript

I'm creating a game that allows two socket connections with Node.js and Socket.io. 我正在创建一个游戏,该游戏允许与Node.js和Socket.io进行两个套接字连接。 There is a "host" and and "join" function. 有一个“主机”和“加入”功能。 First the host connects, but I want to make sure they cannot connect again to another game, so I put in a conditional to check if the game object has been created for that socket. 首先,主机进行连接,但是我要确保它们无法再次连接到另一个游戏,因此我加入了一个条件,以检查是否已为该套接字创建了游戏对象。 For some reason, (with the simplified code I used below), the Game object is not saved with the UserSocket object. 由于某些原因(使用我在下面使用的简化代码),Game对象没有与UserSocket对象一起保存。 I'm assuming it's a scoping issue, but not really sure. 我假设这是一个范围界定的问题,但不确定。

function Game(gameid) {

    this.gameID = gameid;
    this.joined = false;
    this.active = false;
    this.baseball = false;

}

function UserSocket(sock) {

    o = this;

    o.sock = sock;

    o.sock.on('clientData', function (data) {

        o.CreateGame(data);

    });

    o.CreateGame = function (hostdata) {

        console.log('in create game');
        --->console.log(o.game); //*** this call always returns null

        if (o.game) {

            console.log('game already started');  // this never happens
            return false;
        }

        newgame = new Game(hostdata);

        console.log("game object created");
        console.log(newgame.gameID);

        newgame.host = o.sock;
        o.game = newgame;

        console.log(o.game);
        arrGames.push(newgame);

        o.SendToHostSocket("Hosting game: " + newgame.gameID );

    } 

}

You at least need to change: 您至少需要更改:

function UserSocket(sock) {

    o = this;

    ...

to this: 对此:

function UserSocket(sock) {

    var o = this;

    ...

The way you had it, o was an implicit global variable. 你有它的方式, o是一个隐含的全局变量。 If anyone called new UserSocket() a second time, you would overwrite the value in o and then your first socket would no longer work properly. 如果有人第二次调用new UserSocket() ,则将覆盖o的值,然后第一个套接字将无法正常工作。


In Javascript all variables that are intended for use only within a function should be preceded with var upon their first declaration. 在Javascript中,仅打算在函数中使用的所有变量都应在其首次声明时以var开头。 If you leave that out, then they become "implicit global variables" that are accessible to all your code and subject to inadvertently being overwritten. 如果不考虑这一点,那么它们将成为“隐式全局变量”,您的所有代码都可以访问它们,并且会无意间被覆盖。 Implicit global variables are a bad coding practice that often leads to bugs and, in fact, if you run your code in strict mode, this causes an error and the code will not even run. 隐式全局变量是一种不良的编码习惯,通常会导致错误,实际上,如果以严格模式运行代码,则会导致错误,并且代码甚至无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM