Home > Back-end >  Nodejs Set a global function and call a nested function
Nodejs Set a global function and call a nested function

Time:12-24

My Main function

import AppLauncher from './Applauncher'

function Mainfunc() {
 global.app=  AppLauncher()
 global.app.start('index')
}

AppLauncher.js

    function AppLauncher() {
      function start(opts){
              console.log('functions start called with'   opts)
        }
     }

   export default AppLauncher

I want to assign the AppLauncher function as global, and call the start function nested inside it

CodePudding user response:

Constructors are the way to go. You can do something like this:

// AppLauncher.js
function AppLauncher() {
  // run some code...
  // notice `this`
  this.start = function(opts) {
    console.log('start function called with', opts);
  }
}
export default AppLauncher;

In your main function, call it with the new keyword:

import AppLauncher from './AppLauncher';
function Mainfunc() {
  global.app = new AppLauncher();
  global.app.start('index');
}

Constructors can also be written as classes (you can use it the same way as in my last example):

class AppLauncher {
  constructor() {
    // Anything in here gets executed when once you create an object from this class with the `new` keyword
  }
  // Instead of `this` we add a method to the class:
  start(opts) {
    console.log('start function called with', opts);
  }
}

export default AppLauncher;

More about constructors: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

If you don't want to use a constructor, you can also return an object:

// AppLauncher.js
function AppLauncher() {
  // Some code here...
  return {
    start(opts) {
      console.log("function start called with", opts);
    }
  };
}
export default AppLauncher;

And you can use this just like you thought:

import AppLauncher from `./AppLauncher`;
function Mainfunc() {
  global.app = AppLauncher();
  global.app.start('index');
}

As a side note, it's conventional to call constructors with PascalCase, while regular functions are called with camelCase.

  • Related