javascript - 如何让函数在创建时调用自己的函数

标签 javascript class

我有一个函数 PublicGame,我想像类一样使用它。当我创建 PublicGame 时,我通过设置 this.methodName = function 为其提供了一堆方法。唯一的问题是我想在创建 PublicGame 时调用其中一些方法。例如,现在我这样做 this.judge = this.setJudge(),但我知道这在我拥有它的地方不起作用,因为 setJudge 尚未定义。我应该把它放在 PublicGame 的底部吗?我的设计完全不对劲吗?
代码:

'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;
}

最佳答案

如果您在原型(prototype)上定义函数,则无需“等待”定义函数,因为在调用构造函数的代码时实例已经拥有它们

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

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

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

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

因此,除非您的函数需要访问某些“私有(private)”变量(即在构造函数中定义,而不是全局变量),或其他原因需要它,否则在原型(prototype)上定义它而不是在构造函数中定义它,它将是准备使用。

关于javascript - 如何让函数在创建时调用自己的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056575/

相关文章:

javascript - 附加到 JQuery 中的元素

javascript - moment.js isBetween() 方法使用澳大利亚日期格式

java - 如何从单独的类中检索 ArrayList<Item>?

python - 从类方法中提取重复代码

javascript - 在应用程序中使用 HtmlCtrl 时,"scrollHeight"未在 "onscroll"事件处理程序中更新,但在 IE9 中正常工作

javascript - 修改 Geonames 的 JSON Ajax 请求

javascript - 在函数之外存储 getElementById 是个好主意吗?

java - 获取字符串并将其作为一个类运行

c++ - 为什么在对象表达式的上下文中找不到我的构造函数?

javascript - 删除类 onclick ... angular js