Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: IIfe called before class constructor

So I was just playing around with javascript, I have an iife defined withing a class which is being called before the class constructor.

class SomeClass {
  constructor() {
    console.log('Constructor Called.');
  };

  someIife = (() => {
    console.log('iife called');
    return () => { }
  })()
};

const someClass = new SomeClass();

The output is -

iife called

Constructor Called.

Is this by design? I am not sure what is happening.

Seems really interesting, could someone please explain why is this happening.

Thanks.

like image 447
Amol Gupta Avatar asked Aug 22 '26 07:08

Amol Gupta


1 Answers

The constructor function that's generated from your class declaration is effectively this:

  function SomeClass() {
    this.someIife = (() => {
      console.log('iife called');
      return () => { 

      }
    })();
    console.log("constructor called");
  }

Instance variable declarations in the class body are transformed into this.something initializations in the constructor function body. Those initializations happen before the actual constructor body, so that the instance values can be used by the constructor code.

like image 117
Pointy Avatar answered Aug 24 '26 22:08

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!