Reputation: 454
I run the code below in the latest chrome console.
I thought that the Test
class would be declared in root
's scope, so I could then access the constructor via string, yet this is not the case. Could someone please explain, how do I create a new instance with 'Test'
?
(() => {
let root = this
class Test {}
console.log( root['Test'] )
})()
Upvotes: 1
Views: 215
Reputation: 5363
You can attach the class to this
because it is not attached by default.
Then you will be able to access it as Object property.
See code below:
(() => {
this.Test = class Test {
name() {
return "Hi 5";
}
}
console.log('Name is ', new this['Test']().name())
console.log('Or using window ')
console.log('Name is ', new window['Test']().name())
})()
Upvotes: 1
Reputation: 785
(() => {
let root = this;
class Test {}
this.Test = Test;
console.log(root['Test'])
})()
Upvotes: 0