0

I want to give the anonymous function's name that is inside my function based on the parameters passed. For example, if the passed parameter is "nature" then I want to create an anonymous function with that name.

Example code:

function hello(nature) {
    window.nature /* I want this word "nature" to be taken from the parameter passed by the function */ = function () {
        console.log('succes');
    }
}
  • 3
    *'if the passed parameter is "nature" '*: are you talking about a string that is passed as argument, or are you talking about the *name* of the parameter? – trincot May 20 '22 at 18:03
  • 1
    *"create an anonymous function with that name"*: the *name* of a function is not necessarily the same thing as the name of the global property to which you assign that function. Even functions that are not global can have a name... So which are you looking for? A global variable name, or setting the name of the function (`myfunction.name`)? – trincot May 20 '22 at 18:05
  • I'm talking about a string that is passed as an argument and then put in the function name. – Mushlih Almubarak May 21 '22 at 07:40
  • What do you mean with "put in the function name"? You mean the name of the function becomes that, or that there is a variable with that name which gets the function as value? – trincot May 21 '22 at 07:45

2 Answers2

0

Here is an exemple where variable "nature" has value "fn" and parameter passed to "fn" is logged to the console.

function hello(method) {
  window[method] = function (param) {
    console.log(param);
  };
}

hello('fn');
window.fn('success');
Guillaume
  • 166
  • 1
  • 11
0

You can do it by passing a string as parameter. Here how to assign a custom name and a custom function, if needed.

function hello(name, func) {
  window[name] = func;
}

hello('azerty', () => console.log('hello'));
window.azerty() // output 'hello'
NetSkylz
  • 414
  • 2
  • 8
  • With this solution the name of the function is not `azerty`, but `hello`. – trincot May 21 '22 at 07:44
  • @trincot The author wants the name of the function which will be added to the window object to be customisable, which is the case in my answer: you want "azerty" to be the name and then you can call "window.azerty()". The "builder" function is named "hello" because that's what the author provided in is question. – NetSkylz May 21 '22 at 10:03
  • I find it great that you understand the author -- I have been asking about this in above comments, and didn't get a non-ambiguous answer. To me the name of the function is `myfunction.name` and nothing else. – trincot May 21 '22 at 10:14