简体   繁体   中英

Writing jQuery plugin — multiple instantiation

I have a question regarding the local variables for my jQuery plugin. I am pretty sure if I declare them outside the main jQuery function register, then every time the plugin is called it will redefine the variables.

Example:

(function($){
    jQuery.fn.test = function(options){
        if ( options ) { 
            $.extend( settings, options );
          }
        this.each(function(i,item){
            // do whatever i am going to do
        });

    };


    var settings = {
        value1: "hello",
        value2: "word"
    };
})(jQuery);

Say that $(object).test({value1:'newterm'}); is called multiple times.. Am I correct in thinking that every time that method is called, that it will override the settings with the most recently declared settings?

If i want multiple instances of my plugin, do I need to declare everything within the scope of the main jQuery.fn.test = function(){//here} method?

Yes, that is correct, because $.extend will modify settings which is in the closure scope exposed when the jQuery initialization function sets up .test on the global object jQuery. That closure scope is the same everytime you execute .test ; therefore, all objects will retain changes.

It depends on the order you pass objects to $.extend. The first (target) object passed will be modified, in your case the settings object. If you want to keep the defaults:

$.extend(options, settings);

Or to get a brand new object:

var newoptions = $.extend({}, options, settings);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM