Javascript将String转换为Variable Recursive

时间:2015-02-23 10:46:50

标签: javascript html5 canvas

我想用html5 / canvas制作游戏。

这是我的第一次尝试,这个想法非常基础。

我们将图像作为图像对象保存在ImageRepository中。

我们不想手动设置每个图片,如new Image()

var ImageRepository = new function() {
    var images = {
        background: "img/background.jpg",
        planets: {
            earth: "img/planets/earth.png",
            moon: "img/planets/moon.png"
        },
        ships: {
            fighter: "img/ships/fighter.png"
        },
        bullets: {
            fighter: {
                single: "img/bullets/fighter/single.png"
            }
        }
    }

    for(var i = 1; i <= images.length; i++) {

    }
}

这样的基本骨架。

所以,问题是;

如何将此对象转换为this.variable_name

例如:

this.background = newImage();
this.background.src = ourValueInImagesObject;

我们如何使用多级对象来做到这一点?

1 个答案:

答案 0 :(得分:2)

首先,我会将数据集分开。

var repo = {
    background: "img/background.jpg",
    planets: {
        earth: "img/planets/earth.png",
        moon: "img/planets/moon.png"
    },
    ships: {
        fighter: "img/ships/fighter.png"
    },
    bullets: {
        fighter: {
            single: "img/bullets/fighter/single.png"
        }
    }
}

function ImageRepository(repo) {

    // save a copy of this scope
    var _this = this;

    // use this recursive function to iterate over nested objects
    // it's an immediately invoked function into which the repo
    // object is passed. Note that this needs to be a named function.
    // Also note that the new function creates a new scope which is
    // why we needed to save the original scope to a new variable to use later
    var loop = function loop(obj) {

       // loop over the object
       for (var p in obj) {

            // if the 'node' is an object, pass the object
            // back to the recursive function
            if (typeof obj[p] === 'object') {
              loop(obj[p]);
            } else {

              // otherwise add the new images
              _this[p] = newImage();
              _this[p].src = obj[p];
            }
        }
    }(repo);
}

通过将您的回购传递给构造函数来创建新的图像集:

var imageset = new ImageRepository(repo);

This demo使用控制台日志显示结果,而不是创建实际图像,但它应该显示正在发生的事情。