Javascript 将字符串递归转换为变量

Javascript Convert String to Variable Recursive

我想用 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;

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

首先我会分离出数据集。

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 使用控制台日志显示结果而不是创建实际图像,但它应该向您显示正在发生的事情。