4

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

But it doesn't really explain why. So, why is writing code like:

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

preferable to simply:

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

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

Richard
  • 31,629
  • 29
  • 108
  • 145

1 Answers1

2

$ is a jQuery function object or alias of jQuery.(More precisely jQuery function and every function in javascript is an object). see What is the meaning of symbol $ in jQuery?

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

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

Take a simple example.

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

It's all about code organization and behavior.

While if you define

function highlightResults(){xyxyxy;} 

it's not a property of jQuery function object and sits in GLOBAL space

Community
  • 1
  • 1
P K
  • 9,972
  • 12
  • 53
  • 99