0

I have a class like this

"use strict";

class Person {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

And I'd like to create a Person using window like this:

var bob = new window["Person"](0, 15);

Like done here: Instantiate a JavaScript Object Using a String to Define the Class Name

or here: Create object from string

But it's not working. I get the error:Uncaught TypeError: window.Person is not a function

Is this not possible or am I making a stupid mistake?

Community
  • 1
  • 1
Tom Andersen
  • 11
  • 2
  • 5
  • 2
    Are you transpiling with Babel? You likely need to manually attach `Person` to `window`. (Also, why would you do this?) – Evan Davis Jan 26 '16 at 02:46
  • 1
    I can't reproduce your error. See [working JSBin](https://jsbin.com/duwimi/edit?js,console). – Michał Perłakowski Jan 26 '16 at 02:51
  • See the possible duplicate [Create object from string in JavasScript ECMAScript 6](http://stackoverflow.com/q/31776949/1048572) for how to do it properly. If that helped, I'll close. – Bergi Jan 26 '16 at 02:55
  • Yes @Bergi, I don't know what babel is but I'm guessing that's what I'm messing up. You can close it, thanks for your help. – Tom Andersen Jan 26 '16 at 02:59
  • To explain the issue: `class`, `let` and `const` don't create a property on the global object (like `var` does). – Felix Kling Jan 26 '16 at 03:04

0 Answers0