Home > Mobile >  how to Pass a JavaScript function name as parameter and replace function name like parameter
how to Pass a JavaScript function name as parameter and replace function name like parameter

Time:04-17

Its just an experiment

I can pass function name ass parameter but it's called the same name function.

function refreshContactList(id) {
    console.log(`Hello World ${id}`);
}

function addContact(id, refreshCallback) {
    refreshCallback(id);
}

addContact(1, refreshContactList);

like that.


but I want to change the function name, so its changes the name of the function like that ( image )

function addContact(id, refreshCallback) {
    
    function refreshCallback(id) {
        console.log(`Hello World ${id}`);
    }
    
}

addContact(1, refreshContactList);

is there any way to achieve that?

CodePudding user response:

In your picture, you pass not name of function but the reference to this function. If you really want to call the top-level function by the given name (that is, by the string with the name of this function), you can use a cross-platform method that works equally well in node.js, browsers (traditionally, except for Internet Explorer) and other platforms: globalThis:

function a() {
  console.log('a')
}

function b() {
  console.log('b')
}

function callByName(name) {
  globalThis[name]
}

callByName(a)

CodePudding user response:

Is Nested Functions you want?

function addContact(id) {
    function anotherThing() {
        console.log(`Hello World ${id}`);
    }
    
    return { anotherThing };

}

addContact(1).anotherThing();
  • Related