开发者

Why/how is everything $() based in jQuery?

开发者 https://www.devze.com 2022-12-10 10:49 出处:网络
开发者_开发知识库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 fo

开发者_开发知识库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.

0

精彩评论

暂无评论...
验证码 换一张
取 消