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?
Asked
Active
Viewed 213 times
0
-
2'$' is a valid character for a JavaScript function to begin with. – Davin Tryon Sep 24 '13 at 15:14
-
http://stackoverflow.com/questions/6746352/replace-dollar-sign-with-jquery – jackJoe Sep 24 '13 at 15:14
-
How do you make a similar identifier? – Pixeladed Sep 24 '13 at 15:18
-
`$` is just a convenient variable name, nothing more. See http://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names – nullability Sep 24 '13 at 15:18
2 Answers
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
-
Oh ok, so would jQuery variable in the code be an object in order to hold all the function? – Pixeladed Sep 24 '13 at 15:23
-
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