I was wondering, how does the $. in $.ajax({...}); work? it doesnt make sense to me. Sure .ajax as a member make sense but $ isnt a variable name? or is it? How is it defined?
$ is the same as jQuery. That is, you can write jQuery.ajax(...) etc.
The confusing part is $ is a legal character in Javascript variable names. It doesn't have any special meaning, as it does in PHP or Perl, for instance.
From the source:
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
It's a function (first-class object) with properties, such as the ajax
function you mention.
"$" is a valid character for variable names, and as you can see from the code snippet, $
is the same as jQuery
.
$ is one of the only legal characters that can be used in Javascript variable names. JQuery and other libraries take advantage of that initializing $ to be a function that initializes the jQuery object.
If I remember correctly the code looks somewhat like the following:
$ = window.jQuery = function(){
return new jQuery(args);
}
$ This is defined within the jQuery library to be a reference to jQuery shorter. You can download the library and see the first lines:
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
This "window.$", "$" Belongs to the window object environment.
In javascript, functions are objects (that can be contained by variables). As such, they can have properties (and methods which are just properties with functions as values). Try this:
function test () {
alert("hey!");
}
test.foo = function (msg) {
alert("you said: "+msg);
};
test(); //alerts "hey!"
test.foo("123") //alerts ""you said: 123".
//note that I'm not calling test().foo(),
//as test() returns nothing, though it could
//return an object (with a foo() or any other method itself!)
this is sort of what happens with jQuery.
As explained in a number of JavaScript resources, including Mozilla's JavaScript Guide:
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
So the following are all legal (though ill-advised) in JavaScript:
var $ = function() {};
var ____ = 0;
var __$__$ = 1;
function _$_$_$_(_, __, $_$) {
return (_ * __) + $_$;
}
alert(_$_$_$_(3,2,1)); // shows 7