Jump to content

(function() { ... })


omgRawr
 Share

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).

Edited by Deirdre's Dad
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.

Edited by justsomeguy
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.

Edited by Synook
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...