function - jquery - difference between $.functionName and $.fn.FunctionName -


In jQuery, I have seen the following methods of defining jQuery functions:

   

$ .fn.CustomAlert = function () {Warning ('bu!'); }; $ .CustomAlert = function () {Warning ('bu!'); };

I understand that they are related to the jQuery object (or $), but what is the difference between the two?

I'm sure this question has been asked many times before, but I do not have the link Can get it.

indicates $ .fn to jQuery.prototype . Any method or properties that you add becomes available for all instances of jQuery-coated objects.

$ Some add an object or function to itself in the jQuery object.

When you are working with the DOM elements on the page, and your plugin does something for the elements, then use the first form $ .fn.something . When the plugin does not have anything to do with the DOM elements, then the other form is $. Use something . For example, if you have a logger function, it does not have much sense in using it with DOM elements:

  $ ("p & Gt; span ") log ();  

For this case, you just want to add the log object to the jQuery object iself:

  jQuery.log = function (message) {// Enter somewhere;}; $ .log ("very good");  

However, while dealing with the elements, you would want to use another form. For example, if you had a graphing plugin that used to call data & lt; Table & gt; and creates a graph - you $ .fn * will use the form.

$ .fn.plotGraph = function () {// read the table data and generate a graph}; . $ ("# SomeTable") plotGraph ();

On a related note, suppose you had a plugin that can be used with an element or standalone, and you can call it $ MyPlugin or $ ("& lt; Selector & gt;"). MyPlugin () , you can reuse the same function for both.

Say that we want a custom alert, where each alert message. When used as a standalone function, we give it a message as an argument, and when used with the elements, it will be used as the message in the form of the text Uses:

  (function ($) {function myAlert (message) {warning (new date). ToUTCString () + "-" + message);} $ .myAlert = MyAlert; $ .fn.myAlert = function ({return (each (function (myAlert ($ (this) .text ());}}}}}}} ();  

It is wrapped up in the self-performing ceremony, so mer The alert does not spread in the global scope, it re-utilizes the functionality between both an example or plugin forms.

As mentioned by the IIV, this is a return to the jQuery wrapped element Good practice because you do not want to break the chains.

Finally, I got the same question: -)

  • < Li>

  • Comments