0

I've a set of jquery and generally javascript function in a js. Now I want to avoid some of the functions to be available on some condition. For example:

function test () {
    alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
   }
}

Thanks

3
  • 1
    Could you share some more information to check on what you require? A jsfiddle link would be good. Commented Dec 3, 2012 at 16:05
  • Ehrrm.. I'd suggest just to not call the function. Commented Dec 3, 2012 at 16:05
  • Could condition be evaluated within test() itself? Like for instance function test() { if (!condition) { alert("hi"); } }? Commented Dec 3, 2012 at 16:08

2 Answers 2

1

If you want to remove a function without errors (provided the caller of the function doesn't expect a returned result), you might do

function avoid () {
   if(condition)  {
     test = function(){}; // does nothing
   }
}

Note that if your avoid function is in a different scope, you might have to adapt. For example if test is defined in the global scope, then you'd do window.test = function(){};

Sign up to request clarification or add additional context in comments.

1 Comment

And you could add test.old = test to keep the old function
0

I am not sure if I understood your question well but if the call to your test function is within the avoid function like below:

function test () {
    alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
    return false;
   }
   test();
}

Then a simple return false could solve your problem, I am not sure if your functions are using events but if that is the case this is a good post that you can read about preventDefault and return false : enter link description here

if test is at the same level of avoid like below :

function test () {
alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
    return false;
   }
   return true;
}

// below is your functions call
   check =  avoid();

   if(check){
    test();
   }

This post explains how to exit from a function: enter link description here

I hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.