Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - shortcut for calling a function at the same time it is defined

to call a function at the same time it's defined, i had been using:

var newfunc = function() {
    alert('hi');
};
newfunc();

is the following the correct way of combining these 2:

var newfunc = function() {
    alert('hi');
}();
like image 936
Anish Avatar asked Aug 22 '10 08:08

Anish


2 Answers

There could be a number of reasons you wish to do this. I'm not sure what yours are, but let me introduce a couple of favourite patterns:

Pattern #1: A singleton. The function is executed and then becomes a singleton object for use by other components of your code.

var singletonObject = new function() {

    // example private variables and functions
    var variable1 = {};
    var variable2 = {};
    var privateFunction = function() { 
    };

    // example public functions
    this.getData = function() { 
        return privateFunction(variable1, variable2);
    };

    // example initialisation code that will only run once
    variable1.isInitialised = true;
};

Pattern #2: Self-executing anonymous function ... handy for sooo many reasons!

// Declare an anonymous function body. 
// Wrap it in parenthesis to make it an "expression.
// Execute it by adding "();"
(function(){})();

And here's an example that also creates a namespace for your objects. I'm using "NS" as an example namespace:

// declare the anonymous function, this time passing in some parameters
(function($, NS) {

    // do whatever you like here

   // execute the function, passing in the required parameters. 
   // note that the "NS" namespace is created if it doesn't already exist
})(jQuery, (window.NS = window.NS || {}));

You can also set the context of a self-executing function by using .call or .apply instead of the usual parenthesis, like this:

(function($){
    // 'this' now refers to the window.NS object

}).call(window.NS = window.NS || {}, jQuery);

or

(function($){
    // 'this' now refers to the window.NS object

}).apply(window.NS = window.NS || {}, [jQuery]);
like image 109
bboyle1234 Avatar answered Oct 03 '22 15:10

bboyle1234


var newfunc = function f() {
    alert("hi!");
    return f;
}();

Having a named function expressions allows the function to recursively call itself or, in this case, return itself. This function will always return itself, however, which might be an annoyance.

like image 34
adamse Avatar answered Oct 03 '22 16:10

adamse