0

我在 js 中有一组 jquery 和一般的 javascript 函数。现在我想避免某些功能在某些条件下可用。例如:

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

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

谢谢

4

2 回答 2

1

如果你想删除一个没有错误的函数(假设函数的调用者不期望返回结果),你可以这样做

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

请注意,如果您的avoid功能在不同的范围内,您可能需要进行调整。例如,如果test在全局范围内定义,那么你会做window.test = function(){};

于 2012-12-03T16:04:04.300 回答
0

我不确定我是否很好地理解了您的问题,但是如果对您的测试函数的调用在如下所示的避免函数中:

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

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

然后一个简单的 return false 可以解决您的问题,我不确定您的函数是否正在使用事件,但如果是这种情况,这是一篇很好的帖子,您可以阅读有关 preventDefault 并返回 false :在此处输入链接描述

如果测试处于相同的避免级别,如下所示:

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();
   }

这篇文章解释了如何退出函数:在此处输入链接描述

我希望这会有所帮助。

于 2012-12-03T16:14:36.120 回答