简体   繁体   中英

best way to toggle between functions in javascript?

I see different topics about the toggle function in jquery, but what is now really the best way to toggle between functions? Is there maybe some way to do it so i don't have to garbage collect all my toggle scripts?

Some of the examples are:

var first=true;
function toggle() {
   if(first) {
      first= false;
      // function 1
   }
   else {
      first=true;
      // function 2
   }
}

And

var first=true;
function toggle() {
   if(first) {
      // function 1
   }
   else {
      // function 2
   }
first = !first;
}

And

var first=true;
function toggle() {
  (first) ? function_1() : function_2();
  first != first;
}
function function_1(){}
function function_2(){}

return an new function

var foo = (function(){
    var condition
         , body
    body = function () {
        if(condition){
             //thing here
        } else {
            //other things here
        }
    }
    return body
}())` 

Best really depends on the criteria your application demands. This might not be the best way to this is certainly a cute way to do it:

function toggler(a, b) {
   var current;
   return function() {
      current = current === a ? b : a;
      current();
   }
}

var myToggle = toggler(function_1, function_2);
myToggle(); // executes function_1
myToggle(); // executes function_2
myToggle(); // executes function_1

It's an old question but i'd like to contribute too..

Sometimes in large project i have allot of toggle scripts and use global variables to determine if it is toggled or not. So those variables needs to garbage collect for organizing variables, like if i maybe use the same variable name somehow or things like that

You could try something like this..: (using your first example)

function toggle() {
    var self = arguments.callee;
    if (self.first === true) {
        self.first = false;
        // function 1
    }
    else {
        self.first = true;
        // function 2
    }
}

Without a global variable. I just added the property first to the function scope.
This way can be used the same property name for other toggle functions too.

Warning: arguments.callee is forbidden in 'strict mode'


Otherwise you may directly assign the first property to the function using directly the function name

function toggle() {
    if (toggle.first === true) {
        toggle.first = false;
        // function 1
    }
    else {
        toggle.first = true;
        // function 2
    }
}

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