We're switching from MooTools to jQuery at work. I have a coworker that told me never to use $
as the prefix when using a jQuery method (if I understood him correctly). He said that instead, the more appropriate or safer way (I didn't really follow him) was to use jQuery.
.
So instead of $.plugin()
, jQuery.plugin()
should be used, for example.
Why would that be the case? What distinction is he making with $
/jQuery
? Should I forget about the dollar sign as my accessor? Only in certain circumstances?
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.
Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript. jQuery also allows us to add animated effects on our web page which takes a lot of pain and lines of code with JavaScript.
It is said that jQuery is better for DOM manipulation than Javascript, however, after monitoring both of their performances, vanilla JS was found to be faster than jQuery.
Why would that be the case? Is his $/jQuery distinction correct?
Because almost every JavaScript library defines a function called $. When you have many libraries in one document, conflicts may appear. If you are sure that jQuery is and always will be the only script defining that function, I wouldn't have anything against using $.
jQuery defines a nice solution to resolve conflicts: jQuery.noConflict. By using this function you can define your own name, whereby jQuery will be accessible, e.g.
var $jq = jQuery.noConflict(true);
Calling this function will result in restoring previous values for $ and jQuery variables when existed before initializing jQuery. I don't remember if any other libraries try to resolve name conflicts.
If you want to use $ instead of jQuery all the time you can run your code in a separate, private scope that holds the definition of $ by using a self-invoking function.
(function($){ // your code goes here $("body").append("<p>Hello World!</p>"); })(jQuery); // or even jQuery.noConflict()
$ is aliased to jquery and could, in theory, be aliased to something else in another included library or script which may lead to confusion or worse. If you're only using jquery, using $ should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With