创建由变量引用的新函数实例

时间:2012-06-24 18:45:35

标签: javascript function variables object instance

我正在尝试创建一种存储和加载HTML5画布游戏地图的方法。为此,我必须创建一个由变量引用的对象(函数)的新实例。这是我的代码。

    function Map(w, h) {
        if (typeof w == "undefined")
            this.width = 640;
        else
            this.width = w;

        if (typeof h == "undefined")
            this.height = 480;
        else
            this.height = h;

        this.obj = new Array();
        this.x = new Array();
        this.y = new Array();
        this.backgroundColor = "#C0C0C0";
    }

    Map.prototype.addObject = function(cl, xx, yy) {
        this.obj.push(cl);
        this.x.push(xx);
        this.y.push(yy);
    }

    function newInstance(o, x, y) {
        this.tmp = new o(); //This is what doesn't work.
        tmp.x = x;
        tmp.y = y;
        objects.push(tmp);
        tmp.create();
    }

    Map.prototype.load = function() {
        for (var i = 0; i < this.obj.length; i++) {
            newInstance(this.obj[i], this.x[i], this.y[i]);
        }
    }

我希望它可以这样使用:

    //When I create the map.
    var mMain = new Map();

    //This cannot be new Player() and new Block() because I don't want to load the map yet. I'm just creating the map.
    mMain.addObject(Player, 320, 240);
    mMain.addObject(Block, 0, 256);
    mMain.addObject(Block, 32, 256);
    //etc...

    //When I load the map.
    mMain.load();

仅举例说明Player和Block对象的工作原理。

    function Player() {
        this.x = 0;
        this.y = 0;
        //Other variables irrelevant to this problem.
    }
    //Block object code

1 个答案:

答案 0 :(得分:0)

我弄明白了这个问题。在发布之前我忘记检查所有代码,所以我提供了错误的信息。而不是&#34;函数Player()&#34;,我有&#34; var Player = ObjectResource;&#34;因为我希望它扩展ObjectResource函数。我只需将其更改为我发布的内容。