javascript - Is it possible to define AND immediately invoke a function all in 1 swoop? -


i have bit of code on site

$(function () {     (var k = 0; k < ogmap.length; ++k) {         $('#orglist').append($('<option></option>').text(ogmap[k]['orgname']).val(ogmap[k]['orgname']));     } // create organization option memu list of organizations      function updateinfo() {         var newlyselectedorg = $('#orglist option:selected').val();         $('#currorg').text(newlyselectedorg);         var categories = [];         (var k = 0; k < ogmap.length; ++k) {             if (ogmap[k]['orgname'] == newlyselectedorg) {                 categories = ogmap[k]['catnames'];                 break;             }         } // array of strings corresponding categories selected organization in         $('#catlist > option').each(function () {             $(this).remove();         }); // remove current <option> list items categories <select> list         (var k = 0; k < categories.length; ++k) {             $('#catlist').append($('<option></option>').text(categories[k]));         } // add new <option> list items categories <select> list     }      updateinfo();      $('#orglist').change(function () {         updateinfo();     });  }); 

because need define updateinfo function , run because it's part of preprocessing page. know that

var updateinfo() = function() { ... } 

or equivalently

function updateinfo() { ... }  

define function , don't run it, ,

(function() { ... }) 

runs keeps anonymous.

is possible both define , run it?

for reason, having

function updateinfo() { ... }; updateinfo(); 

just rubs me wrong way, gives me sense i'm not using best practice.

no, not possible declare function , invoke in same run.

however, if don't need declare variable (to used after call), can use immediately-invoked function expression (iiefe).

if need refer function inside body (for recursive calls or similar), can still name it, making iinfe.

for actual use case, attaching event handler , invoking initialisation immediately, can use different pattern - trigger event right away:

$('#orglist').change(updateinfo).change();  // instead of $('#orglist').change(updateinfo); updateinfo(); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -