2

Say we have a class in the global scope

class SampleClass {
    constructor(a) {
        this.a = a;
    }
}

After this declaration, the class can be instantiated in the global scope like:

var obj = new SampleClass(a); //works

But the same declaration doesn't work inside a function in the global scope, as in:

function sampleFunc() {
    var obj = new SampleClass(a); //doesn't work
    //...
}

It throws the error:

Uncaught ReferenceError: SampleClass is not defined

How can I create an object of SampleClass from inside the function sampleFunc?

I am confused because SampleClass is declared in the global scope, so I expected it to be visible inside sampleFunc.

  • I get error as `"TypeError: Class constructor SampleClass cannot be invoked without 'new'`.. How did you get the error you posted? [Link](https://jsbin.com/kuyumamora/3/edit?js,console). Also the error I got, is expected and self explanatory.. You were supposed to call it like `new SampleClass(a)`.. – Arup Rakshit Aug 25 '18 at 14:51
  • My bad, I forgot to add the new keyword in the question, which I have in my source code. I fixed it. – Netal Jubalin Aug 25 '18 at 15:13
  • Ok, then it will be a loading issue.. Probably, you are trying to call the function before the definition is available.. – Arup Rakshit Aug 25 '18 at 15:15
  • I can run the sampleFunc without a ReferenceError if I declare the SampleClass above sampleFunc. Are you declaring SampleClass in the same file ? – Axnyff Aug 25 '18 at 15:15
  • 1
    The class definition appears before the function, as in the example. Both are in the same file. However, the function is called from a point above the class definition. Is that the reason? – Netal Jubalin Aug 25 '18 at 15:19
  • Ok, I moved the function that calls `sampleFunc` below the declaration of `SampleClass` and I don't get the error anymore. I didn't realize Javascript is so sensitive to the ordering of declarations. – Netal Jubalin Aug 25 '18 at 15:22
  • 1
    Yes that's the problem, the class is not initialized yet so it won't work – Axnyff Aug 25 '18 at 15:24
  • @NetalJubalin Yes, it's in the [temporal dead zone](https://stackoverflow.com/a/31222689/1048572). You cannot instantiate a class before you defined it [for good reasons](https://stackoverflow.com/q/35537619/1048572). – Bergi Aug 25 '18 at 17:19

0 Answers0