Reputation: 6720
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?
Upvotes: 2
Views: 402
Reputation: 44205
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);
Upvotes: 3
Reputation: 1557
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.
Upvotes: 6