How is jQuery's $ a function and an object?

I mean object as in {} [object Object]. How does it do $(selector) and $.fn.init at the same time?

Can you give me a simple example please?


Solution 1:

This isn't unique to jQuery, but an aspect of javascript. All functions are objects. E.g.:

var f = function() { alert('yo'); }
f.foo = "bar";

alert(f.foo); // alerts "bar"
f();          // alerts "yo"

Solution 2:

Javascript is an object oriented language, so functions ARE objects, just fancy ones that you can call.

foo = function() { console.log("foo") }
foo.bar = function() { console.log("bar") }
foo() //=> prints "foo"
foo.bar() //=> prints "bar"

Solution 3:

$ is a function. a method of $ can return any thing.

For example:

$ = function() {
     return {
                 foo : function() { return 'baa'; },
                 r1: 1,
                 r2 : 'string'
            }
};

typeof $ <- function 
typeof $() <- object
typeof $().foo <- function 
typeof $().foo() <- string
typeof $().r1; <- number 
typeof $().r2 <- string

Solution 4:

jQuery or $ is an function(you know $ is an alias of jQuery).

// Define a local copy of jQuery
jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
},

In Javascript, everything is an object even function too. Hence You can directly add properties to function.

   jQuery.find = function () {
   }

Solution 5:

It is an object.

$ holds different functions.

You can test this yourself by making your own object:

var $ = {
     select: function(id){return document.getElementById(id);}
}

function $(id){
      return $.select(id);
}