简体   繁体   English

如何在创建函数时调用其自己的函数

[英]How to have function call its own function on its creation

I have a function PublicGame which I'd like to be using similar to a class. 我有一个想要与类相似的PublicGame函数。 When I create PublicGame I give it a bunch of methods by setting this.methodName = function. 当我创建PublicGame时,我通过设置this.methodName = function给出了很多方法。 The only thing is that I want to call some of these methods when the PublicGame is created. 唯一的事情是我想在创建PublicGame时调用其中一些方法。 Right now for instance I do this.judge = this.setJudge() , but I know this wont work where I have it because, setJudge isnt defined yet. 例如,现在我执行this.judge = this.setJudge() ,但是我知道这在我有的地方不起作用,因为setJudge尚未定义。 Should I put this at the bottom of PublicGame? 我应该把它放在PublicGame的底部吗? Is my design totally off? 我的设计完全关闭了吗?
Code: 码:

'use strict';

// var GameSockets = require(‘GameSockets’);
var Games = {};
var id_counter = 0;
var minPlayers = 3;
var maxPlayers = 6;

function PublicGame (players) {
    this._id = id_counter++;
    this.players = players;
    this.gameSocket = new GameSockets.registerPlayers(this.players, this._id, this.playerDisconnects);

    this.judge = this.setJudge();

    this.killGame = function() {
        delete Games[this._id];
    };

    // When a player presses leave game
    this.playerExits = function(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove),1);

        // If less than min players
        if (this.players.length < minPlayers) this.killGame();

        // If less than max players
        if (this.players.length < maxPlayers) {
                this.needsPlayers = true;
        }

       gameSockets.kickPlayer(playerToRemove);
    };

    // When a player disconnects without warning, e.g. closes window
    this.playerDisconnects = function(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove),1);

        // If less than min players
        if (this.players.length < minPlayers) this.killGame();

        // If less than max players
        if (this.players.length < maxPlayers) {
                this.needsPlayers = true;
        }
    };

    this.selectJudges = function() {
        this.judge = this.players.pop();
        this.players = this.players.unshift(this.judge);
    };

    this.setWinner = function(winner) {
        this.winner = winner;
    };



    Games[this._id] = this;
}

If you define your functions on the prototype than you do not need to "wait" for the functions to be defined because the instance will already have them when the constructor's code is called 如果在原型上定义函数,则不需要“等待”要定义的函数,因为在调用构造函数的代码时实例将已经具有它们

function PublicGame (players) {
  //...
  this.judge = this.setJudge();
}

PublicGame.prototype.killGame = function(){
  //...
};

PublicGame.prototype.playerExits = function(playerToRemove){
  //...
};

PublicGame.prototype.setJudge = function(){
  //do whatever
  return whatever;
};

So unless your functions need to access some "private" variable (ie defined within the constructor, not a global variable), or other reason requiring it, define it on the prototype instead of defining it in the constructor and it will be ready to use. 因此,除非您的函数需要访问某些“私有”变量(即在构造函数中定义,而不是全局变量)或其他需要它的原因,否则请在原型上定义它,而不是在构造函数中定义它,即可使用。

You have to use javascript prototype ! 您必须使用javascript原型

Read the comments in the code sample. 阅读代码示例中的注释。

 /* * utils functions * * dont take care about that **/ var el = document.getElementById('dbg'); var jj = function(val,sep){return JSON.stringify(val , null , sep || '')} var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'}; var counterId = 0; /************************************************************************/ // You have to use prototype // here an example of what you can achieve // we create a Player 'class' var Player = function( name ){ this.id = counterId ++; //<-- an attribute this.name = name; //<-- an attribute this.setLevel(5);//<-- a method called at 'instanciation' return this; }; // a method available at instanciation time Player.prototype.setLevel = function(level){ this.level = level; return this; }; // we create a new Player named Toto var Toto = new Player('Toto'); log('Toto = ' + jj(Toto));//<-- utility function just to log // we create a new Player named Jane var Jane = new Player('Jane'); log('Jane = ' + jj(Jane)); //<-- utility function just to log // we change the Level of Jane Jane.setLevel(12); log('Jane.setLevel(12)');//<-- utility function just to log log('Jane = ' + jj(Jane));//<-- utility function just to log 
 <div id='dbg'></div> 

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

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