1

According to jQuery API I see that $() is collection of matched elements. But what is $ ? Example from imagesLoaded library below.

if ( $ ) {
  $.fn.imagesLoaded = function( options, callback ) {
    var instance = new ImagesLoaded( this, options, callback );
    return instance.jqDeferred.promise( $(this) );
  };
}
igor_rb
  • 1,821
  • 1
  • 19
  • 34
  • 1
    See http://stackoverflow.com/questions/4797956/how-does-jquery-achieve-making-an-alias-for-the-jquery-function – Pramod Aug 19 '13 at 11:55
  • 3
    The question is not, "what is `$`", the question is, what is the difference between `$` and `$()`. – Daniel W. Aug 19 '13 at 11:58
  • 1
    The code shown could have several possible results: (1) if `$` has not been defined it'll give a `ReferenceError: $ is not defined` and execution will not continue after the `if`; (2) if `$` has been defined but has a falsy value the code inside the `{}` will not be executed; (3) if `$` has a truthy value but is not `jQuery` it'll probably give some kind of type error (unless `$` is an object that already has a `fn` property that is also an object); (4) if `$` exists as an alias for `jQuery` the code will work as intended. – nnnnnn Aug 19 '13 at 12:08

3 Answers3

1

$ is referencing the jQuery Object, like an alias.

Objects do have constructors.

Calling $('#test'); results in jQuery('#test');

See this for constructor explanation: Constructors in JavaScript objects

From the jQuery Source @github:

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
}
Community
  • 1
  • 1
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
1

$ is a reference to the jQuery function (in your case), so this condition just checks whether a variable or function named $ evalutes to true.

Example:

function test() {
  // do something
}

if (test) {
}

The expression test references the function.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • Note that `if (variableName) {` is _not_ the correct way to test whether a variable exists because if it doesn't exist you get a `ReferenceError: variableName is not defined`. – nnnnnn Aug 19 '13 at 12:03
  • @nnnnnn You're right, therefore I put "exists" in double quotes. I've just rephrased it ;) It should be right, now. – ComFreek Aug 19 '13 at 16:17
1

According to the jquery's code:

window.jQuery = window.$ = jQuery;

so $ is actually a pointer to jQuery global object.

Krasimir
  • 13,306
  • 3
  • 40
  • 55