将类的引用传递给另一个类并使用其方法

时间:2016-02-13 01:17:33

标签: javascript design-patterns semantics anti-patterns

假设您正在制作游戏。您想尝试而不是污染全局范围并可能限制用户轻松改变游戏的能力(对于客户端而言是可疑的)。您觉得模块对于您的目的可能是不必要的。在实例化期间将引用传递给另一个类以访问其方法是不好的做法吗?

受挫的例子:

//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 Entity;
})();

//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();
});

原谅这个半生不熟的例子。如果你最终得到了'Entity'类的许多实例,那么对'Level'的所有引用,虽然是同一个实例,但是开始占用更多内存吗?还有其他陷阱吗?另一种方法是实现某种可以访问的接口,允许类相互通信。

0 个答案:

没有答案