2

I've looked into the jQuery sources and I don't exactly undestand how it can use $ symbol as function in selectors

$el = $('#element');

and as objects in helper-functions

$.each([1, 2, 3], function(num) { ... });

$ function creates new jQuery.fn.init, which is somewhere in prototypes, I'm confused.

mikatakana
  • 503
  • 9
  • 22

2 Answers2

5

A function in Javascript is an object, so you can add properties to a function.

Example:

function lib(x) {
  return x + 1;
}

lib.add = function(a, b){
  return a + b;
};

Now you can use it both as a function and as an object having functions:

var n = lib(4); // n = 5

var m = lib.add(7, 8); // m = 15

jQuery does the same, just using $ as a name instead of lib as I used in the example.

The $ name is normally an alias for the jQuery name, and jQuery.fn is a reference to the prototype for the jQuery function. So when jQuery.fn.init is called, it's the same as jQuery.prototype.init.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Out of curiosity, how would you write `lib` as an object literal? – fuzzybabybunny Jan 02 '15 at 22:39
  • @fuzzybabybunny: If you do that, then it's an object that isn't a function. A function is an object, but you can't make any object be a function. – Guffa Jan 02 '15 at 22:42
  • Haha, ok, now I'm officially confused. Everything is an object, no? I figured that everything needs to start off as being `{ //keys and values }`... – fuzzybabybunny Jan 02 '15 at 22:49
  • @fuzzybabybunny: What you get from an object literal is an object of the type `Object`. A function declaration creates an object of the type `Function`. You can't turn an object of type `Object` into an object of the type `Function`. An object of the type `Function` on the other hand inherits from the type `Object` so it has all its properties. – Guffa Jan 02 '15 at 22:58
  • mind = blown. Very cool. – fuzzybabybunny Jan 02 '15 at 23:17
0

$ is just a shorthand for jquery, which represents a function.

In $el = $('#element');, $ (which is the same as jquery) is the function name that takes the selector as a function argument, resulting in the syntax $();

When executing this selector function, jQuery.fn.init (initializer function) is executed and returns the jQuery object, exposing the different selector methods that you can use.

html_programmer
  • 18,126
  • 18
  • 85
  • 158