0

I feel like I've only ever seen this here on SO, but I can't seem to find any documentation on it. The code I am talking about is stuff like this:

$(function foo(){
    alert('foo');
});

Is there anything to that or is that just something that novices do because they think jQuery is a language? There is no scope change. It just seems completely unnecessary. Is there any method that you can invoke on this like:

$(function foo(){ alert('foo'); }).someMethod();

The closest thing I can think of is $.proxy, but that doesn't use this syntax. Am I right, is this completely unnecessary?

lbstr
  • 2,822
  • 18
  • 29
  • It's equivalent to `$(document).ready(function(){})` [Documented here](http://api.jquery.com/ready/) – Michael Berkowski Jun 14 '12 at 20:27
  • possible duplicate of [What does $(function() {} ); do?](http://stackoverflow.com/questions/7642442/what-does-function-do) – Felix Kling Aug 19 '12 at 20:40
  • Possible duplicate of [What does $(function() {} ); do?](https://stackoverflow.com/questions/7642442/what-does-function-do) – lbstr Sep 19 '19 at 19:34

1 Answers1

3

That's how you invoke a function after DOM initialization. It's equivalent to

$().ready(function() { ... } );

EDIT: From the documentation:

All three of the following syntaxes are equivalent:

 - $(document).ready(handler)
 - $().ready(handler) (this is not recommended)
 - $(handler)

See: http://api.jquery.com/ready/

lbstr
  • 2,822
  • 18
  • 29
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • @lbstr -- thanks for the corrections, but is "syntaxes" really the plural of "syntax". Wiktionary agrees with you, but I can't help thinking "syntaces"... – Michael Lorton Jun 15 '12 at 00:00
  • @malvolio I don't think syntax is an English word, so it's different pluralized (I know that's not a word, but I'm Dutch). – 11684 Jun 15 '12 at 05:48
  • @Malvolio -- I agree. Syntaxes looks weird and Chrome underlines it as a typo. But, I guess the plural of tax is taxes, so we'll have to live with it :) I guess I could have said: "Pick a syntax from the list below; they're all the same". – lbstr Jun 15 '12 at 14:59
  • 1
    @lbstr -- there's a long pointless joke that ends, "The zookeeper wrote, 'Enclosed please find one mongoose. Also enclosed: another mongoose'." – Michael Lorton Jun 15 '12 at 15:37