Search code examples
javascriptwindoweval

window["object.something"] not working for objects javascript


Hi I just can't figure this one out.

I need to use the window["evaluate string into js object"] because I am converting a web Application into a ChromeOS Chrome app and they do not let you use eval() to do their content security policy.

My problem is that for basic varibles it is fine, example:

var a = "foo";

var b = window["a"];

This will put "foo" into b no problem. But as soon as I have an object (both global or local) it doesn't work, so if 'a' was an object the code would like something like this:

a.test = "foo";

var b = window["a.test"];

That will not work.

Is there a reason for this? I can't seem to find much info on window[] in general so wondering if anyway has any insight or at least can point me in the right direction to look.

Thanks


Solution

  • window[] doesn't work on namespaced functions, so if you try to evaluate window['a.test'] it would fail. A proper alternative is to use window['a']['test']. In case you're indefinite of number namespaced objects you're going to use, you can create a simple function that would split the string from . and create a window object for each part. Example :

    var str = 'namespace.service.function';
    var parts = str.split(".");
    for (var i = 0, len = parts.length, obj = window; i < len; ++i) {
        obj = obj[parts[i]];
    }
    console.log(obj);