简体   繁体   中英

Why do javascript libraries like jQuery generally prefer anonymous functions over named ones?

There are two common ways to declare a javascript function

Way 1: Named Function

function add(a, b) 
{                     
  return a+b;
}

To call the above function we use add(3,4);

Way 2: Anonymous function

var add = function(a, b) 
{                     
    return a + b;
} 

To call this function we again use add(3,4);

Both produce the same result. I always go with way 1 as I learned javascript this way. But most of the new javascript libraries like jQuery seem to use way 2.

Why is way 2 preferred over way 1 in most of the javascript libraries? As per my understanding both produce the same behaviour. The only difference is in way 1, the function is available to code that runs above, where the function is declared, which is not true in Way 2. Is this the only reason new javascript libraries uses the the way 2, so that they can ensure their libraries are included first and then call their function?

Anonymous functions are used to comfortably define objects. The reason libraries often drop the named declaration and only use anonymous (even when its not specifically needed) is to improve code readability, so you dont have two ways to declare one thing in your code.

var x = function() {
   //constructor
}

x.y = function() {
   //first method
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM