A function call based on a string containing the function name

var foo1,foo2; switch (fn) { case "fade" : foo1 = "fadeOut"; foo2 = "fadeIn"; break; case "slide" : foo1 = "slideUp"; foo2 = "slideDown"; break; } eval("$('.cls1')." + foo1 + "();"); currentSlideIndex = currentSlideIndex + n; eval("$('.cls1')." + foo2 + "();"); 

Is there a better way to achieve this without using eval? I am not a big fan of using eval, if absolutely necessary.

+7
javascript jquery
source share
5 answers

Since the function names stored in foo1 and foo2 are properties of the object returned by $('.cls1') , the following should work:

 $('.cls1')[foo1](); 

Same thing with foo2 .

+4
source share
 $('.cls1')[foo1](); currentSlideIndex = currentSlideIndex + n; $('.cls1')[foo2](); 
+4
source share

You do not need to use eval , you can just use the conventions of the accessor property :

 $('.cls1')[foo1](); 
+4
source share

You can use the syntax:

 $('selector')[foo1](); 

However, another approach to dynamically invoking a method is to create a new method that divides

 (function() { $.fn.someFunc = function(what) { switch(what) { case 'fadeOut': $(this).fadeOut(); break; // etc default: // handle an unknown value } } })(jQuery); $('.cls1').someFunc('fadeOut'); 

This will allow you to quickly control what happens, instead of passing something like foo1.

+1
source share

You can use this strategy according to your needs:

 function doFade() { alert('fade'); } function doFadeIn() { alert('fadeIn'); } var fns = { 'fade': doFade , 'fadeIn', doFadeIn }; function callSomething(what) { fns[what](); } // callSomething('fadeIn'); => alerts 'fadeIn' 
+1
source share

All Articles