Lee2808 Lee2808 - 25 days ago 8
Javascript Question

Javascript - Is it possible to make a function call itself after definition and then be referenced as a function elsewhere in scope

Consider the following:

(function () {

var _searchUsers = function () {
console.log("Searching...");
};

var search = (function () {

_searchUsers();

this = function () {
_searchUsers();
}

})();

//Some onclick event handler
function click () {
search();
}
})();


Is there a more concise way of achieving this feature in javascript? I want to declare a function and have it execute straight away and that's why I've made it an IIFE (self executing function) but I also want to reference that function elsewhere in scope later on the in the lifetime of the script, say when a user clicks a button and the "click" function is invoked above.

Example use-case:

I have a table of users, on page load I want to make an AJAX request to go and fetch the users immediately, I also want the user's to be able to load the users at a click of a button, let's say I have a search box which sends that text up to my API and returns user's who's name matches the given text.

The above snippet handles this requirement, I'm just wondering if there is a more concise method to achieve this, and i'm also just interested to see what people post as an answer.

Answer

This is another option:

(function () {
    var _searchUsers;            // Declare the variable like you did already
    (_searchUsers = function (){ // Assign the function, and immediately call it.
        console.log("Searching...");
    })();

    //Some onclick event handler
    function click () {
        _searchUsers();
    }
})();
Comments