Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use (function() { .... }()); [duplicate]

Tags:

javascript

Possible Duplicate:
How does the (function() {})() construct work and why do people use it?

Why do the modern JavaScript files use constructs like:

(function () {
   // some real code
 }());

I.e. I understand that an anonymous function is being created and then called immediately, with no parameters passed... But why do it this way and not just call some real code? And what is the outer pair of round brackets for?

In particular I'm staring at the file js/start.js at Github:

(function() {
    "use strict";

    wooga.castle.GRID_UNIT = 48;
    wooga.castle.IMAGES_BASE_URL = "images/entities/";

    (function () {
        var style = document.createElement('div').style,
            prefix;
        var candidates = {
            webkit: 'webkitTransform',
            moz:    'MozTransform', // 'M' is uppercased
            ms:     'msTransform',
            o:      'oTransform',
            '':     'transform'
        };
        for (var prefix in candidates) {
            var candidate = candidates[prefix];
            if ('undefined' !== typeof style[candidate]) {
                wooga.castle.prefix = prefix;
                wooga.castle.prefixedTransform = candidate;
                break;
            }
        }
    }());

    // XXX why the 2 wrapped "function"s here? XXX

    wooga.castle.isNativeWrapper = function() {
        var result = !wooga.castle.capabilities.desktop && !wooga.castle.capabilities.android && (! /Safari/.test(navigator.userAgent));
        wooga.castle.isNativeWrapper = function () {
            return result;
        };
        return result;
    };
}());

With my basic JavaScript and jQuery skills I understand the single commands listed above, but I don't get why are they wrapped inside of several functions. Can't we just call:

    "use strict";

    wooga.castle.GRID_UNIT = 48;
    wooga.castle.IMAGES_BASE_URL = "images/entities/";
    var style = document.createElement('div').style,
        prefix;
    var candidates = {
        webkit: 'webkitTransform',
        moz:    'MozTransform', // 'M' is uppercased
        ms:     'msTransform',
        o:      'oTransform',
        '':     'transform'
    };
    for (var prefix in candidates) {
        var candidate = candidates[prefix];
        if ('undefined' !== typeof style[candidate]) {
            wooga.castle.prefix = prefix;
            wooga.castle.prefixedTransform = candidate;
            break;
        }
    }

    wooga.castle.isNativeWrapper = !wooga.castle.capabilities.desktop && !wooga.castle.capabilities.android && (! /Safari/.test(navigator.userAgent));
like image 389
Alexander Farber Avatar asked Jun 26 '12 14:06

Alexander Farber


People also ask

What does duplicate mean in Java?

Duplicate code as the name suggests is a repetition of a line or a block of code in the same file or sometimes in the same local environment.

What is duplicate function declaration?

Duplicate declarations are simply an equivalent restatement of an interface specification, and that has no effect on code which depends on that interface.

How does duplicate work in R?

The R function duplicated() returns a logical vector where TRUE specifies which elements of a vector or data frame are duplicates. ! is a logical negation. ! duplicated() means that we don't want duplicate rows.

What is a JavaScript function?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.


1 Answers

This is done so the code inside doesn't interfere with variables in the global scope.

For example:

var myLibrary = {};
var _privateVar = [];

Now, both of these are global. But, I don't want that. So, if I make a function, I can make a new scope.

(function(){
    window.myLibrary = {}; // global
    var _privateVar = []; // private
}());
like image 192
Rocket Hazmat Avatar answered Oct 19 '22 22:10

Rocket Hazmat