Can I name a JavaScript function and execute it immediately?

前端 未结 8 1754
谎友^
谎友^ 2020-11-28 04:04

I have quite a few of these:

function addEventsAndStuff() {
  // bla bla
}
addEventsAndStuff();

function sendStuffToServer() {
  // send stuff
  // get HTML         


        
8条回答
  •  忘掉有多难
    2020-11-28 04:16

    Your code contains a typo:

    (function addEventsAndStuff() {
      alert('oele');
    )/*typo here, should be }*/)();
    

    so

    (function addEventsAndStuff() {
      alert('oele');
     })();
    

    works. Cheers!

    [edit] based on comment: and this should run and return the function in one go:

    var addEventsAndStuff = (
     function(){
      var addeventsandstuff =  function(){
        alert('oele');
      };
      addeventsandstuff();
      return addeventsandstuff;
     }()
    );
    

提交回复
热议问题