Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why write code Jquery like this

Tags:

jquery

Why write code Jquery like this?

(function ($) {
    $(function () {
     .......
    });
})(jQuery);
like image 637
Nomit Avatar asked Mar 31 '13 06:03

Nomit


People also ask

Why we use this in jQuery?

HTML. The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.

Why do you prefer jQuery over JavaScript?

jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is easier to use compared to JavaScript and its other JavaScript libraries. You need to write fewer lines of code while using jQuery, in comparison with JavaScript.

Why do people not use jQuery anymore?

JQuery is useful, but what killed it was it's widespread use. Vanilla Javascript kept updating so that things that made jQuery special became things that you found in Javascript without jQuery. So, it started becoming obsolete.

Does jQuery make coding easier?

jQuery is Easy to Learn In addition to extending the functionality of your pages, jQuery helps your code stay simple, clean, and easy to read. Legible code is essential when you're getting started, as it makes it easier to spot your mistakes!


1 Answers

This is called a closure to avoid conflicts with other libraries which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {
   $(function () {
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.

from the docs:

it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.

This is generally used to author plugins. Read out more here

like image 150
Jai Avatar answered Sep 30 '22 01:09

Jai