Tutorial :jquery calling a function from var value


(function($) {    $.fn.myFoo= function (o){      this.element = $(this)        options = jQuery.extend({           name: "defaultName",           size: 5,           global: true        }, o);        _min = function (){ //am i private method?          alert('dud');      }      max = function (){ //am i public method?          alert('max');      }      return this.o(); //o= 'max'  }  })(jQuery);  

Question 1 = is there a way to call the max method/function above if i was to use this line $('#id').myFoo('max'); Question 2 = i know that on jquery widgets an underscore "_" would mark the method as private. is this the same case on the $.fn ?

note that the line return this.o(); it is wrong its just there to demonstrate what i would like to accomplish


Your code has some issues:

First, when you run it, you will end up with three global variables, max, _min and options.

JavaScript is function-scoped, but you should use the var statement to declare variables, if you don't use it, and the identifier you make the assignment is not found in the scope-chain, they will become properties of the Globlal object (window).

Second, I think you want to invoke a function passed as a String argument, if is that, you I would recommend you to use an object to group your functions, and be able to get them, if you just define your functions as variables, they are not bound to an accessible object (technically variables, arguments and function declaration identifiers are bound to the non accessible Variable Object), e.g.:

(function ($) {    $.fn.myFoo= function (o){      var privateFunction = function (){         alert('private');      };        var functions = {        _min: function (){           alert('_min');        },        max: function (){          alert('max');        }      };          functions[o](); // invoke the function      // ...      return this; // preserve the jQuery method "chainability"    };  })(jQuery);  

Edit: If you want to declare a "private function", (not invokable through your String argument), you can simply declare it as a variable in the $.fn.myFoo function.

It will be usable by all your "public functions" (all the members of the functions object) but you won't be able to execute it using your o argument.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »