How to prevent a plugin from conflicting?

3

I'm writing a plugin for tables called easyTable .

After understanding the basic operation of a plugin and how it can perform a thread I read in the documentation that to avoid the conflict it should look like this:

(function ( $ ) {

    $.fn.easyTable = function() {
        // methods...
        return this;
    };

}( jQuery ));

I would like to understand why the plugin should be inside this function, so it seems to make it anonymous.

Documentation: How to Create a Basic Plugin

    
asked by anonymous 10.03.2016 / 18:08

2 answers

6

What makes the anonymous function is that it has no name :) See:

(function ( $ ) {

Where is the name? It does not, so it's an anonymous function. The parentheses in the loop are required by a syntax detail (if the line starts with function , the function must have a name). More details on this in this other question: What is the difference between the functions var name = function () and function name ()?

The reasons for the plugin to be inside the anonymous function:

  • All variables you create, with var , within the anonymous function will not be available globally. That's fine, your plugin's code gets encapsulated and you do not risk interfering with other scripts on the page.

  • The anonymous function is immediately invoked (note ( jQuery ) ) at the end), and receives as argument the jQuery object. Only within the function this object is available as $ . Thus, your plugin may refer to or jQuery as $ without running the risk of referring to another library that also uses the $ identifier - for example, prototype .

  • 10.03.2016 / 18:20
    2

    Because you do this you create a local scope and any and all var or function you create belongs to this location only, you will have access to the global space from outside, but the outside space will not have access to your local - unless you say that the variable is global.

    This is known as encapsulation.

    Modularization in JavaScript
    When should you use var in javascript?

        
    10.03.2016 / 18:19