Jump to content

(function() { ... })


omgRawr

Recommended Posts

You know how some JavaScript files start with this:

(function()  {...})

Well, I don't get what that does. I know that it creates a nameless function (please correct me if I'm wrong) but other than that, I have absolutely no clue why they do this. What is the purpose of doing that?

Link to comment
Share on other sites

I've never seen that exactly as you have it written, but I've seen/used things very similar, using array/object literals (basically, JSON syntax). Example:

fa=[	function(){		// do something;	},	function(){		// do something;	},	function(){		// do something;	}];// And you call one of the functions in the array like this:fa[0]();

Using the new Array() constructor would make it look more like your example. Eg:

fa=new Array (	function(){		// do something;	});

Especially if you changed the placement of the parens (but I wouldn't like that look).

Link to comment
Share on other sites

In addition to defining the function, it's usually also executed immediately:(function() {})();That's generally used to execute whatever code you want to run inside its own scope so that it doesn't interfere with other defined variables or functions. That's also one way to define objects and classes in a certain namespace.

Link to comment
Share on other sites

  • 1 month later...

That is lambda* notation - it is just saying "assign the following function to the variable 'something', so it can be called later by invoking 'something()'". It is the same as writing function something() { ... }.*article not entirely relevant, but it's where the term came from.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...