Andrew Rockwell
Andrew Rockwell

Reputation: 454

Javascript class declaration scope confusion

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

Answers (2)

Tareq
Tareq

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

Marcin Malinowski
Marcin Malinowski

Reputation: 785

(() => {
  let root = this;
  class Test {}
  this.Test = Test;
  console.log(root['Test'])
})()

Upvotes: 0

Related Questions