What is the purpose of a self executing function in javascript?

前端 未结 19 2847
清酒与你
清酒与你 2020-11-21 04:22

In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...
         


        
19条回答
  •  遇见更好的自我
    2020-11-21 04:49

    Given your simple question: "In javascript, when would you want to use this:..."

    I like @ken_browning and @sean_holding's answers, but here's another use-case that I don't see mentioned:

    let red_tree = new Node(10);
    
    (async function () {
        for (let i = 0; i < 1000; i++) {
            await red_tree.insert(i);
        }
    })();
    
    console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
    

    where Node.insert is some asynchronous action.

    I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).

提交回复
热议问题