jQuery newbie: what does jQuery(function($) { … }) means?

后端 未结 5 1537
旧时难觅i
旧时难觅i 2020-12-13 14:11

I know in jQuery, $(callback) is the same as jQuery(callback) which has the same effect as $(document).ready().

How about

5条回答
  •  不知归路
    2020-12-13 14:49

    jQuery(function($) {
    
    });
    

    is the safest version of all three. It makes $ the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $ symbol.

    I think it was also added fairly recently, don't remember seeing it before.

    These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){}) is the original one, and it matches the underlying javascript API.

    "$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.

提交回复
热议问题