How does jquery $ act as an object as well as a function in javascript?

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.

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

How a single identifier $ acts as an object function as well?

+4
source share
2 answers

First of all: jQuery (or its alias $ ) is a function. This is very important because functions are first-class objects in JavaScript. And since they themselves are objects, they have the ability to obtain properties and methods just like any other object. For instance:

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

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

+4
source

This is not true.

$ just a function.

It also has prototype functions that can be used, since a function can have some other function in it (since the function is an object in itself).


You can do:

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

to see all attached functions (and properties).

+3
source

All Articles