Question

Can somebody explain to me what this does in javascript?

 (function (x,y){}(x,y));

or this

  // global import
  (function ($, YAHOO) {
         // now have access to globals jQuery (as $) and YAHOO in this code
  }(jQuery, YAHOO));

I have never seen something similar in other languages like java or c++

Was it helpful?

Solution

function(x, y) { } is an anonoymous function.

(x, y) calls that function, passing x and y as parameters.

OTHER TIPS

The purpose of the second code block is to make jQuery available as $ (without defining $ globally) and importing YAHOO in the local scope to make variable lookups a bit faster.

Besides that, it creates a new scope so any variables defined with var inside will not be global.

The first code block is often used in this way to create new variables, e.g. when you are in a loop and need to create a variable with the current i value for a callback:

for(var i = 0; i < 10; i++) {
    (function(i) {
        setTimeout(function() {
            alert("number " + i);
        }, 1000 * i);
    })(i);
}

Without that new scope you'd have the same i everytime and thus alert "number 10" 10 times.

The first one calls an anonymous function, which takes 2 arguments and doesn't do anything, with x and y as argument.

The second does the same thing. It uses $ as the first argument name, and passes jQuery as the argument value. It's thus possible, inside this function to use $ to refer to the jQuery object. It's a way to alias variables to another name inside a function.

C# has a similar concept, called a Lambda expression.

public static Func<int> Foo()
{
    int a = 1,
        b = 2;

    return () => a + b;
}

It's a generic, first-class function (by first class function, it is meant that the function itself is returned, not the result thereof) that is declared anonymously.

In this case, I also show you what's called a closure - the returned method encloses the 'local' variables a and b, allowing them to persist when Foo goes out of scope. In many languages, anonymous methods implement closures.

Anonymous methods are really cool too - you can perform behavior injection, as in this benchmark method:

public static TimeSpan BenchmarkMe(Action timeThis)
{
    Stopwatch sw = Stopwatch.StartNew()
    timeThis();
    sw.Stop;

    return sw.Elapsed;
}

You can pass an anonymous function that returns a TimeSpan into this method, which will perform a benchmark for a single pass against it. Nifty, eh?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top