有没有办法在JavaScript中使用另一个函数结束函数?

时间:2011-09-17 20:13:20

标签: javascript function terminate

我希望有一个函数可以在调用特定函数之前检查条件是否为true。我的目标是在另一个函数中有一行代码(被调用的函数)。此函数应在执行任何其他代码之前运行。这是一些伪代码来证明我的意思:

function checkFunction(){
//checks if a condition is true if so end function, else continue function
} 
function aFunction(){
checkFunction();
//some code
}

我知道我可以创建一个包含返回的条件语句,但如果可能的话,我想尽量保留它。

谢谢你们的时间。

5 个答案:

答案 0 :(得分:1)

没有什么专门针对你想要的东西而设计的,无论如何它都是针对不良实践的。但是你可以通过写下这样的东西来简单地说明:

function aFunction()
{
   if (!checkFunction()) return;
   //some code
}

答案 1 :(得分:0)

你可能想要一个类似assert的函数,但反之亦然:

function stopIfTrue(x) {
    if(x === true) throw "stop function"; // can be any string
}

然后:

function aFunction(){
    stopIfTrue(something); // if 'something' is true an error will be thrown; function will exit
    //some code
}

答案 2 :(得分:0)

您可以做的一个技巧是动态更改其他功能。所以

function make_wrapped(before, after){
    return function(){
        if(before()) return;
        after.apply(this, arguments);
    }
}

//set aFunction to be the new function
aFunction = make_wrapped(checkFunction, aFunction);

编辑:我误解了这个问题。这可能比你需要的更复杂。

答案 3 :(得分:0)

我会这样做:

function checkFunction(){
  return (condition);
} 

function aFunction(){
    if(!checkFunction()) return;
    //some code
}

答案 4 :(得分:0)

如果你要做的是这个:

function aFunction()
{
    if(checkFunction())
    {
        return;
    }
    //somecode
} 

不使用aFunction()中的return,你可以这样做:

function aFunction()
{
    if(!checkFunction())
    {
        //somecode
    }
}