JavaScript instantiates class without usage React Native

Tags: , , ,

I have the next problem/question in React Native:

I have the next class, let’s say it A that looks like this:

    export default class A {
        static shared = A.shared || new A()
        constructor() {
            console.log('in constructor')
        testFunction = () => {
           console.log('in test function')

        testFunction2 = () => {
           console.log('in test function 2')

My A class in used in B class like this:

export default class B {
    static shared = B.shared || new B()

    makeAPIRequest = (parameters, valueCallback, errorCallback) => {
        console.log('in B req')

And the makeApiRequest function from B class in used in App.js like this:

const makeRequest = () => {
    B.shared.makeAPIRequest(parameters, responseCallback => {
      // do logic here...
    }, errorCallback => {
      // do logic here

And this makeRequest function is placed as an onPress action.

My question is: At the first render of the app, my constructor console.log and called function console.log are printed in terminal. Shouldn’t this happen just before I call the makeRequest function is App.js that calls the makeAPIRequest from B class that instantiate the A class?

If someone can explain me the logic behind this, will be pretty appreciated.


A is instantiated as static dependency of itself so basically that happens just after class is loaded, if you want to make it lazy instantiated you need to do something like:

class A {
    static get shared() {
        if (!this.__instance) {
            this.__instance = new this();
        return this.__instance;

Source: stackoverflow