instantiation of object in Javascript by string

29 views Asked by At

I have a bit of code in Javascript:

   class testClass {
        constructor() {
            this.getter = new window["testGetter"]();
        }
    }
    class testGetter {
        constructor() {
            console.log("success");
        }
    }
    var x = new testClass;

When I run it, I get an error "window.testGetter is not a constructor". Why?

Explanation: This is obvioiusly a very simplified version of what I want to do. It is important to be able to hand in a string with the name, in this case "testGetter".

I have tried to declare testGetter before testClass, but that didn't help. Obviously, testClass is instantiated in the last line and the entire code has been loaded into memory.

EDIT and SOLUTION: Pointy's comment is absolutely correct. console.log(window) confirmed this. Not sure if this is very elegant, but I changed my code to

const testclass = class {
    constructor() {
        this.getter = new window["testGetter"]();
    }
}
const testGetter = class {
    constructor() {
        console.log("success");
    }
}
window.testGetter = testGetter;
var x = new testclass;

thus manually setting testGetter as a window-property. Now it works. (Sorry, can't seem to answer my own question)

0

There are 0 answers