Search code examples
javascriptjquerypluginsglobal-variablesprivate

private variable in jQuery plugin


I'm making a jQuery plugin in which one each elements should have their own variables. I believed the correct way to do so was:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>test 1</div>
<div>test 2</div>
<script language="javascript">
$.fn.menu = function(options) {
    var defaults = {i : 0};
    this.each(function(){
        var parameters = $.extend(defaults, options); 
        $(this).on("click", function(event){parameters.i++;alert(parameters.i);});
    });
};
$("div").menu();
</script>

but it doesn't work: the parameters object is global and so shared between all elements for which the plugin is called.

What's wrong in this example?


Solution

  • Using var parameters = $.extend(defaults, options);, parameters is reference to (extended) defaults object.

    Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend().

    You need to create a new object reference, passing empty one to jQuery extend() method:

    var parameters = $.extend({}, defaults, options);
    

    This is equivalent to:

    var parameters = $.extend(JSON.parse(JSON.stringify(defaults)), options);