0

I am very new to jquery.When I go through the sample jquery plugins, I noticed variety of function declaration syntax.Those are follows:

(function($){
  function function_name1()
  {
      //function body 
  }

  var _function_name2  = function(options){
      //function body 
  };

  $.fn.function_name3 = { 
             function_name4:function(){ //function body },
             //function body 
  };

  $.fn.function_name5 = function(){
             //function body 
  }
}(jQuery));

I am only aware of the function_name5 syntax.So please help me to find out the difference between the others too.Thanks in advance.

1
  • 1
    _function_name3 is a misnomer as it's an object which holds a property called function_name4 that contains a function. For more detail, this link may help Commented Oct 20, 2016 at 8:39

1 Answer 1

1

The following is actually a function syntax,

function function_name1()
  {
      //function body 
  }

To avoid the above function falls in a globe scope we are wrapping the same with an immediate function invocation as below which means the function itself will be invoked immediately by itself.

(function($){

   ....

}(jQuery));

Below one is basically a function variable and called as anonymous function.

var _function_name2  = function(options){
      //function body 
  };

The reason because of is when error occurs inside the function the stack trace won't show the variable name and instead it will show as anonymous function. But you can get the function name for the same with below syntax.

var _function_name2  = function _function_name2(options){
      //function body 
  };

The below one is not actually a function to be called directly instead they will be called with any dom element or element array and the $(this) inside the function will return the same dom element(s). These are normally called as jquery plugins.

$.fn.function_name5 = function(){
             //function body 
  }

Hope you understood.

Sign up to request clarification or add additional context in comments.

2 Comments

:Your explanation is superb :-)
@CelinVeronicca Thanks :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.