Home > Back-end >  Accessing the name of the function when multiple functions are returned
Accessing the name of the function when multiple functions are returned

Time:06-19

I have a basic function, that can be called around my project using different names - tiger, lion, dog.

I'd like to access the name of the triggered name within the function its self.

For example:

I can run demo.tiger('Hello', {1:1}) and like to access the tiger name from within the trigger function.

Thanks

const demo = ({ }) => {

    function trigger (message, context) {

        console.log(message, context);

    }

    return {
        tiger: trigger,
        lion: trigger,
        dog: trigger
    }

}

CodePudding user response:

As @Barmar suggested, you have to pass it through as an argument if you really want it.

const demo = () => {
  function trigger(message, context, caller) {
    console.log(message, context, caller);
  }

  return {
    tiger: (message, context) => trigger(message, context, 'tiger'),
    lion: (message, context) => trigger(message, context, 'lion'),
    dog: (message, context) => trigger(message, context, 'dog'),
  };
};

const x = demo();

x.tiger('a', { 1: 1 });
x.lion('a', { 1: 1 });
x.dog('a', { 1: 1 });

  • Related