Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can jQuery behave like an object and a function?

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.

like image 378
js-coder Avatar asked Jan 04 '12 21:01

js-coder


People also ask

What is the difference between the jQuery function and the jQuery object?

A jQuery object is an object returned by the jQuery function. A jQuery object represents a set of document elements and can also be called a “jQuery result”, a “jQuery set”, or a “wrapped set”. “the selected elements”

Is jQuery a function?

jQuery is() methodThe method returns true if there is atleast one match; otherwise, it returns false. The is() method does not create a new jQuery object. Instead, it allows us to test the jQuery object's contents without any modification. It is frequently used in callbacks like event handlers.

How do you object in jQuery?

Another way to make objects in Javascript using JQuery , getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be: var box = {}; // my object var boxes = []; // my array $('div. test'). each(function (index, value) { color = $('p', this).

What is the functionality of the jQuery function?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.


2 Answers

Functions are also objects, so $.each can be defined in a similar way as an Object.

JavaScript is a prototypical language. For jQuery, this means that every instance of $ inherits methods from jQuery.prototype.See Notes

A very rough demo, to achieve the similar behaviour:

(function() { // Closure to not leak local variables to the global scope     function f(a, b) {         //Do something     }     // Prototype. All properties of f.prototype are inherited by instances of f.     // An instance of f can be obtained by:    new f, new f(), Object.create(f)     f.prototype.removeClass = function(a) {         return a;     };     function $(a, b) {         return new f(a, b); // <--- "new f" !       }      $.each = function(a) {         alert(a);                  };     window.$ = $; // Publish public methods })();  //Tests (these do not represent jQuery methods): $.each("Foo");                   // Alerts "Foo" (alert defined at $.each) alert($().removeClass('Blabla'));// Alerts "Blabla" 

Notes

jQuery's root method is defined as follows (only relevants parts are shown):

(function(win) {     var jQuery = function (selector, context) {         return new jQuery.fn.init(selector, context, rootjQuery);     };     //$.fn = jQuery.fn is a shorthand for defining "jQuery plugins".     jQuery.fn = jQuery.prototype = {         constructor: jQuery,         init: function( /* ..parameters.. */ ) {              //.... sets default properties...         }         //....other methods, such as size, get, etc...         //.... other properties, such as selector, length, etc...     };     jQuery.fn.removeClass = function() { // (Actually via jQuery.fn.extend)         // ... method logic...     };  //...lots of other stuff...      win.$ = win.jQuery = jQuery; //Publish method })(window); 

The advantage of the prototype method is that it's very easy to chain methods and properties. For example:

$("body").find("div:first").addClass("foo"); 

A method to implement this feature could be:

$.fn.find = function(selector) {     ...     return $(...); }; 

If you're interested in jQuery's real implementation, have a look at the annotated source code:

  • jQuery core - Definitions of the constructor and base methods.
  • jQuery.fn.extend is used to add removeClass, etc. to jQuery.
  • jQuery 1.7.1.
like image 159
Rob W Avatar answered Sep 21 '22 12:09

Rob W


All functions work this way.

function fn() {     alert("hi mom"); }  fn.foo = "bar"; 
like image 44
recursive Avatar answered Sep 24 '22 12:09

recursive