How is it that jQuery can do $(\"#foo\").addClass(\"bar\")
and $.ajax()
?
I\'m creating a micro javascript framework and want to create a new in
$ = function(arg) { console.log("$ function called with " + arg); }
$.ajax = function(arg) {console.log("$.ajax called with " + arg);}
$('foo');
$.ajax('bar');
http://jsfiddle.net/ac7nx/
I don't think there's any magic here. $
is just a name for the global function. Just keep in mind that in javascript, functions are first class objects that can have their own properties, including sub-functions, which is what $.ajax
is.
Since you mentioned the constructor function, I should note that there are no OO objects being used here, just regular functions (no new
keyword), so constructor functions don't play into this. If you are using the new
keyword, that is probably where you are getting confused. If you want $('#foo')
to return a new object, then inside the $
function's code you should create a new object using new
and return that, which is what jQuery does, but the $
function itself is not a constructor and should not be called with new
. Or in the case of something like $('#someID')
, inside that function jQuery is getting an element object from the DOM and then returning that object, but still $
is just a regular function whose return value is an object, not a constructor function.