How to prevent a plugin from conflicting?

Asked

Viewed 113 times

3

I’m writing a plugin for tables called easyTable.

After understanding the basic workings of a plugin and how it can perform a chaining li in the documentation that to avoid conflict it should look like this:

(function ( $ ) {

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

}( jQuery ));

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

Documentation: How to Create a Basic Plugin

  • 1

    It seems to me that you are confusing what happens, this template will not prevent conflicts in your plugin, IE, if there is another plugin jquery called easyTable will still conflict. What the model prevents is the conflict between jQuery lib and another lib that uses $ (and it is still necessary that you invoke noConflict), the response of bfavaretto explains how this works.

2 answers

6


What makes the function anonymous is that it has no name :) Look at this:

(function ( $ ) {

Where’s the name? No, so it’s an anonymous function. The surrounding parentheses are needed for a syntax detail (if the line starts with function, the function needs to have a name). More details on this in this other question: What is the difference between the functions var name = Function() and Function name()?

Reasons for the plugin to be inside the anonymous function:

  1. All variables you create, with var, within the anonymous function will not be available globally. This is good, the code of your plugin is encapsulated and does not risk interfering with other scripts present on the page.

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

  • But if all the created variables are within the plugin do not have the need to use this, why they belong only to the scope of the plugin, or is wrong ?

  • Correct, if all is declared within the function assigned to the $.fn.easyTable, is all restricted to this scope. In this case, you only lose the conflict prevention between jQuery and other libraries (see commenting of Brunorb above).

  • +1,Now I understand, in my case I will declare only to prevent conflicts with other libraries.

2

For by doing this you create a local scope and any and all var or function that you create belongs solely to this site, you will have access to the global space outside, but the outer space will not have access to your site - unless you say that the variable is global.

This is known as encapsulation.

Modularization in Javascript
When to use var in javascript?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.