jQuery or $ seems to be a function:
typeof $; // "function"
And it acts like one:
$('div').removeClass(); // $ constructs a new object with some methods like removeClass
But when I drop the function parentheses it behaves like an object:
$.each(/* parameters */); // $ is an object with some methods like each
I’d like to know how this is possible and how I can implement this behaviour to my own functions.
Functions are also objects, so
$.eachcan be defined in a similar way as an Object.JavaScript is a prototypical language. For jQuery, this means that every instance of
$inherits methods fromjQuery.prototype.See NotesA very rough demo, to achieve the similar behaviour:
Notes
jQuery’s root method is defined as follows (only relevants parts are shown):
The advantage of the
prototypemethod is that it’s very easy to chain methods and properties. For example:A method to implement this feature could be:
If you’re interested in jQuery’s real implementation, have a look at the annotated source code:
jQuery.fn.extendis used to addremoveClass, etc. to jQuery.