Are jQuery utility functions preferable to regular function definitions?

This jQuery course recommends defining your own jQuery utility functions as a good way to organize your code.

But this does not explain why. So why write code like:

$.highlightResults = function(seats) { // } $.highlightResults('/.seating-chart a'); 

more preferable:

 function highlightResults(seats) { // } highlightResults('/.seating-chart a'); 

Is the course wrong, or is there a good reason to write it this way?

+4
source share
1 answer

$ - jQuery function object or jQuery alias (more precisely, jQuery function and each function in javascript is an object). see What is the meaning of the $ character in jQuery?

  $.highlightResults => highlightResults is a property of jQuery object. 

By defining any function as a property of a jQuery function object, you can access jQuery and all the jQuery 'this' properties / functions associated with it inside your function.

A simple example.

 $.property1 ='a'; $.property2 ='b'; $.highlightResults = function(){ var concat = this.property1 + this.property2; }; 

All about code organization and behavior.

If you define

 function highlightResults(){xyxyxy;} 

it is not a jQuery function object property and is located in GLOBAL space

+2
source

Source: https://habr.com/ru/post/1388045/


All Articles