It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this
keyword would change meaning, e.g. in
var someClass = function() {
this.property = something;
this.update = (function(obj) {
function() {
$('.el').each(function() {
$(this).html( obj.property );
});
};
)(this);
};
While I want to refer to this.property
inside the $('.el').each()
, this
changes meaning within that scope and refers to the current DOM element that is being looped through with .each()
. So by passing this
as a parameter into the IIFE (and calling that parameter obj
) I can use obj.property
to refer to what is this.property
when outside the scope of $('.el').each( ..., function() { ... });
.
Let me know if that makes sense or if you have any questions :)