jquery - Meaning of (function(){ in Javascript - Stack Overflow

I'm looking to understand the difference between this code:(function() {and this code:$(function()

I'm looking to understand the difference between this code:

(function() {

and this code:

$(function() {

Does the first example run the code after document ready, as the second does? Or does it simply scope the function and nothing more?

I'm looking to understand the difference between this code:

(function() {

and this code:

$(function() {

Does the first example run the code after document ready, as the second does? Or does it simply scope the function and nothing more?

Share Improve this question edited Feb 5, 2014 at 11:09 Itay 16.8k2 gold badges56 silver badges72 bronze badges asked Feb 5, 2014 at 11:04 BarneyBarney 1,8485 gold badges31 silver badges51 bronze badges 1
  • stackoverflow./a/2937256/1719246 Here he explain very well – softsdev Commented Feb 5, 2014 at 11:11
Add a ment  | 

7 Answers 7

Reset to default 5

The first example is a closure, it's a design pattern monly used in JavaScript. In the second one you're calling the $ function giving another function as parameter (jQuery will execute it as soon as the document is ready, since it's an alias of $(document).ready(function () {})).

This is an example of closure:

(function () {
    var foo = 'foo';
    var bar = 'bar';
    window.foo = foo;
})();    // Those () mean that you're calling this anonymous function

console.log(typeof foo);    // Logs 'string'
console.log(typeof bar);    // Logs 'undefined', since 'bar' is internal to the closure's
                            // scope and was not exposed like was 'foo'

And this is an example of $(function () {}):

$(function () {
    alert('Document ready');
});

Check these pages:

  • How do JavaScript closures work?
  • https://api.jquery./jquery/#jQuery3

Your first example is just calling the anonymous function straight away, it allows you to do something like (demo):

(function(test) {
    alert(test);
})('asd')

Whereas the second example you've provided is a jQuery specific call which is run after the DOM is ready - it's essentially a shorthand for $(document).ready(function(){}); (see here)

The first approach, is using self executing anonymous functions.

  1. These methods are executed / called immediately.
  2. These are primarily used to prevent global scope / namespace.
  3. These are usually called once.

More info about self executing anonymous functions go through http://markdalgleish./2011/03/self-executing-anonymous-functions/

The second approach, we are calling jQuery short version of the ready method.

There are three version of calling jQuery ready method ( Source: jquery api )

$( document ).ready( handler )
$().ready( handler ) (this is not remended)
$( handler )

For More info about the jQuery ready method go through http://api.jquery./ready/

 (function() {

This javascript closure which is self executing anonymous function, runs immediately

 $(function() {

jQuery factory function which accepts function as a parameter and runs after DOM is ready

(function() {
    // Code goes here
}());

This is an "immediate function", meaning that is is executed immediately after it is defined. It is also an anonymous function in that it has no name.

This construct is used to provide a variable scope for the script that does not pollute the (usually) global namespace. This is monly referred to as a "closure". Not polluting the global namespace is a good practice, as it prevents mixing up variable names and inadvertently messing with the operation of other scripts.

$(function() {
    // Code goes here
});

This is a shorthand for jQuery's $(document).ready(function() { /* code goes here */ }). It executes the code within only when the entire DOM has been rendered, and is considered ready. Usually you can just omit this if your script is inserted at the very end of the <body>.

The first would typically run the code immediately, but only because of the code you have not shown, at the end of the anonymous function definition. It would be invoked because of:

(function() { doSomething(); } ());

Note this runs immediately, NOT after the document is loaded. The trailing empty parens invoke the function, with zero parameters, just as when you call myFunction(). It is typically written this way just to "scope" variables. For example, you may wrap your entire javascript file like this to protect it from other included files.

In the second example, the $ is actually a function. It is a synonym for "jQuery", so $() is just like jQuery(). jQuery actually also runs this function immediately, with the anonymous function definition as the parameter. What jQuery IMMEDIATELY DOES when you pass it a function definition like this, is queue that function definition to run when the document ready event fires.

The first:

(function() {

Is for self-invoking function (an anonymous function that call itself), like:

(function(){  // some code… })(); 

The Second:

$(function() {

Is an jQuery specific DOM ready event handler function, like the jQuery $(document).ready function.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742303574a4418494.html

相关推荐

  • jquery - Meaning of (function(){ in Javascript - Stack Overflow

    I'm looking to understand the difference between this code:(function() {and this code:$(function()

    15小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信