0

How can jquery run a function when ever it sees $ in the script file? $ is not a javascript key character how come when ever $ appear, jquery run its function? do you need to read the script file in some way then eval it? Is it possible to remake this with another symbol?

Pixeladed
  • 1,773
  • 5
  • 14
  • 26

2 Answers2

6

The jQuery JavaScript file has the following line in it:

window.jQuery = window.$ = jQuery;

Meaning that the window-scoped $ variable will be assigned to the jQuery namespace, in which all the jQuery functions are placed under. This is why you can use jQuery in your code as well as $.

You could do this easily yourself by the same method and another character symbol, even:

window.$$ = jQuery;

would mean that jQuery is now assigned to $$, etc.

Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
2

$ symbol may be used as a name of a function. So, this is a valid javascript:

var $ = function(selector) {
    console.log("selector");
}
$("body");

The other interesting thing in jQuery is that implements the chaining pattern.

Krasimir
  • 13,306
  • 3
  • 40
  • 55