Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Function like Objects i.e. "$" can be used as a function e.g. $() as well as an object $

Tags:

javascript

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!
like image 944
Drew Avatar asked Dec 23 '22 02:12

Drew


2 Answers

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
    }
}
like image 180
John Millikin Avatar answered Jan 19 '23 00:01

John Millikin


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.

like image 21
John Hartsock Avatar answered Jan 18 '23 22:01

John Hartsock