4

Possible Duplicate:
How can jQuery behave like an object and a function?

In jquery we can use $ as a function as well as a namespace. for example both of these use-cases are valid.

  1. $("div").html("<b>Wow!</b> Such excitement...");
  2. var trimmed = $.trim(someString);

How can one identifier $ act as an object as well as a function at the same time?

Community
  • 1
  • 1
SunnyShah
  • 28,934
  • 30
  • 90
  • 137
  • 4
    All functions in JavaScript are objects. You can create your own function, and then attach properties to it just like you would an object. – Pointy Dec 27 '12 at 13:57

2 Answers2

4

First things first: jQuery (or its alias $) is a function. This is very important because functions are "first-class" objects in JavaScript. And since they are objects themselves, they have the ability to be given properties and methods just as any other object. For example:

var f = function() {};

f.h = function(x) {
    console.log(x);
};

This is what allows jQuery to work its magic. In addition, through the use of inheritance, we have the potential to chain methods like you show in your first example. $(selector) returns a jQuery "interface" (technically [object Object]) based on the value of selector which, off of which, we can run methods such as .html, .css, and .toggle to name a few.

David G
  • 94,763
  • 41
  • 167
  • 253
3

It is not.

$ is only a function.

It has prototype functions as well which can be used, since a function can have other function as a part of it (since a function is an object in and of itself).


You can do:

console.log( Object.getOwnPropertyNames($) );

to see all of the attached functions (and properties).

Naftali
  • 144,921
  • 39
  • 244
  • 303