Why/how is everything $() based in jQuery?
开发者_开发知识库I know a bit of JavaScript, and can work fine with jQuery. I just don't get why everything is referenced from $()
. My understanding is that $
is never needed in JavaScript (unlike for example PHP, where every variable is prefixed with $)
.
I've looked through the source code, and it doesn't really make sense. Is it just that $
is the function name (for example, it could have easily have been jQuery()
, but they selected $?
) I assume not, though, as I don't think $
is valid in function names in JavaScript?
$
is just a global variable that's also a reference to the jQuery function, it's $
on purpose so it's less to type. $
is perfectly valid for a function name in ECMAScript:
function $(){}; alert(typeof $);
Note that if you're using multiple libraries you can use function scope to avoid clashing dollar sign variables, eg:
jQuery.noConflict();
(function($){
$('body').hide();
})(jQuery);
$()
is the same as jQuery()
. Also, $
is a valid function name.
精彩评论