4

Questions in the title. I've always wondered and failed to find out from the jQuery source. How this is done.

To reiterate. In jQuery: how does the "$" become a function e.g."$()" as well as an object "$."

I can create it one way OR the other like so...

var $ = function(){
    return {each:function(){console.log("Word")}}
}
// $.each(); FAIL!
$().each(); // Word


var $ = {
    each:function(){console.log("Word")}
}
$.each(); // Word
//$().each(); FAIL!
Drew
  • 1,420
  • 1
  • 11
  • 14
  • 2
    In javascript, **functions are objects**. They are simply a special type of object which support interaction using a method-call syntax. Javascript's object/function unification makes possible a host of other features, like closures, currying, and higher-order methods. – LBushkin Jun 01 '10 at 21:14

2 Answers2

9

Start with the basic function:

var $ = function(expr) { return $.select(expr); }

Then, add extra functionality to it:

$.select = function(expr)
{
    console.log("selecting " + expr);
    return $; // TODO: perform selection
};

$.each = function()
{
    console.log("Called $.each()");
};

You can see how this pattern is used in jQuery by looking at the source:

var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        var match, elem, ret, doc;

        // Handle $(""), $(null), or $(undefined)
        if ( !selector ) {
            return this;
        }

        // contents of init() here
    }
}
John Millikin
  • 197,344
  • 39
  • 212
  • 226
2

in javascript a function is an object. you can create a function with properties, other functions (methods). just write this up in Javascript and look at the type of myfunc

var myfunc = function() {
 //do stuff
}

when you look at the type of myfunc in Firebug you will see that the myfunc is an object.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
John Hartsock
  • 85,422
  • 23
  • 131
  • 146