vendredi 12 février 2016

Passing references of a class to another class and using its methods

Let's say you're making a game. You want to try and not pollute the global scope and possibly limit the user's ability to easily alter the game (doubtful with client-side). You feel like modules might be unnecessary for your purposes. Is it bad practice to pass references to a class to another class during instantiation to access its methods?

Contrived example:

//game.js

var Game = (function () {
    function Game() {
        this.currentLevel = null;
        this.score = 0;
    }

    Game.prototype.addScore = function (num) {
        this.score += num;
    };

    Game.prototype.goToLevel = function (diff) {
        this.currentLevel = new Level(this, diff);
    };

    Game.prototype.returnHome = function (level) {
        this.currentLevel = null;
    };

    return Game;
})();

//level.js

var Level = (function () {
    function Level(game, difficulty) {
        this.game = game; //reference to game
        this.difficulty = difficulty;
        this.entities = [];
        this.load();
    }

    Level.prototype.load = function () {
        this.addEntity({name: 'tim', power: 23, difficulty: this.difficulty});
    };

    Level.prototype.leave = function () {
        this.game.returnHome();
    };

    Level.prototype.addEntity = function (options) {
        this.entities.push(new Entity(this, options));
    };

    Level.prototype.removeEntity = function (entity) {
        for(var x = 0; x < this.entities.length; x++) {
            if(this.entities[x] === entity) this.entities.splice(x, 1);
        }
    };

    return Level;
})();

//level.js

var Entity = (function () {
    function Entity(level, options) {
        this.level = level; //reference to level
        this.options = options;
    }

    Entity.prototype.kill = function () {
        this.level.removeEntity(this); // anti-pattern?
        this.level.game.addScore(34.53); // too closely coupled?
    };

    return Level;
})();

//main.js

var Main;
(function (Main) {
    var game = null;

    function documentIsReady() {
        start(); // Start the game
    }

    function start() {
        game = new Game();
        game.goToLevel('hard');
    }

    return {
        documentIsReady: documentIsReady
    }
})(Main || (Main = {}));

$(document).ready(function () {
    Main.documentIsReady();
});

Forgive the half-baked example. If you end up with many instances of the 'Entity' class, do all the references to 'Level', though the same instance, start taking more memory? Are there other pitfalls? Another method would be to implement some kind of interface that you can access that allow classes to talk to each other.

Aucun commentaire:

Enregistrer un commentaire