I’m writing a jQuery plugin and getting regularly confused by the scope of certain functions (as is tradition when using jS).
A short example should help:
(function ( $ ) {
var methods = {
init: function ( options ) {
var settings = $.extend ({
a: 100,
b: 200
}, options);
return this.each(function(){
var $this = $(this);
var return_value = $this.plugintest("method_1", settings);
$this.plugintest("method_2", settings, return_value);
});
},
method_1 : function ( settings ) {
var method_1_value_1 = settings.a * 10,
method_1_value_2 = settings.a * 20;
return method_1_value_1;
},
method_2 : function ( settings, old_return_value ) {
// WHAT IF I WANT BOTH method_1_value_1 AND method_1_value_2 in here?
}
};
$.fn.plugintest = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call ( arguments, 1 ) );
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.robottest' );
}
};
}) (jQuery);
See method_2. I want to access the values that I created in method_1, however I can only return 1 value – should I create a Global variable of some sort? What is the ‘best’ way to do this?
Variables are visible in the function where they are declared (i.e. the function where their
varstatement appears) and in any functions that are declared within that function.Here’s an example:
You should never use global variables (i.e. variables that aren’t declared with the
varstatement inside a function). These are visible to all other code in your document. However, as long as you enclose everything in afunctionand always usevaryou’re safe.