Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

javascript - I'd like to understand the jQuery plugin syntax

The jQuery site lists the basic plugin syntax for jQuery as this:

(function( $ ){    
  $.fn.myPlugin = function() {      
    // there's no need to do $(this) because
    // "this" is already a jquery object

    // $(this) would be the same as $($('#element'));

    this.fadeIn('normal', function(){    
      // the this keyword is a DOM element    
    });    
  };
})( jQuery );

I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:

  1. If you replace function($)... with a variable, say "the_function", the syntax looks like this:

     (the_function)( jQuery );
    

    What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?

  2. It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function(x){ 
    x...
}

is just a function without a name, that takes one argument, "x", and does things with x.

Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.

function($){ 
    $...
}

I'll put it in parentheses to make sure it parses as an expression:

(function($){
    $....
})

To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:

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

Just for kicks, let's call this function and pass in jQuery as a variable:

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

This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.

WHY?

  • Because writing jQuery every time you want to do something with jQuery is tedious.

WHY NOT JUST WRITE $ = jQuery?

  • Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...