Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript anonymous function syntax

What is the difference between the following two blocks?

// block 1
{
    console.log("anonymous block");
}

// block 2
(function anon() {
    console.log("anonymous block 2");
})();

I ran this in Netbeans (using the node.js plugin) and they both seem to work...

like image 256
Jeff Storey Avatar asked Jan 27 '26 23:01

Jeff Storey


2 Answers

The difference is that you can use the latter form to hide global variables without destroying them.

For example, suppose you're using the jQuery library, which by default aliases its main namespace to $. If you wanted to use $ for a different purpose without changing how $ is normally used, you could do something like this:

(function($) {
    // Use $ without clashing with the jQuery object.
})(someObject);

In fact, it's also useful for one other purpose. Since undefined is NOT a reserved word in JavaScript, it can be given a value and lose its purpose. So you could simply not pass a value into an undefined parameter, and you know it will behave properly without clashing with a global value.

undefined = "some not-undefined value";    // you'd have to be an idiot to do this but I've seen it done
(function(a, b, undefined) {
    console.log(typeof(undefined) === "undefined");   // true
})(someA, someB);
like image 95
Platinum Azure Avatar answered Jan 30 '26 12:01

Platinum Azure


The first creates a block, which is not the same as a function. You can use anonymous self-executing functions to create local, private variables and return an interface from it. It's called the Module Pattern.

var Module = (function() {

    var method = function() { console.log("anonymous block"); },
        someOtherMethod = function() {};

    return { // return our interface as an object literal
        method: method,
        someOtherMethod: someOtherMethod
    };
})();

Module.method(); // "anonymous block"

We can call it, keeping the variables method and someOtherMethod isolated from the global scope. It's one of the most important, useful features of object-oriented programming in JS.

like image 35
David G Avatar answered Jan 30 '26 13:01

David G