Is there a way to end a function with another function in JavaScript?
I would like to have a function that checks if a condition is true run before a specific function is called. My goal is to have one line of code (the function being called) in another function. This function should run before any other code is executed. Here is some pseudocode to demonstrate what I mean:
function checkFunction(){
//checks if a condition is true if so end function, e开发者_高级运维lse continue function
}
function aFunction(){
checkFunction();
//some code
}
I know I can make a conditional statement that contains a return, but I would like to keep it this short if possible.
Thank you guys for your time.
There's nothing designed specifically for what you want, and its verging on bad practice anyway. But you could get it pretty succinct by just writing something like:
function aFunction()
{
if (!checkFunction()) return;
//some code
}
You might want an assert
-like function, but then the other way round:
function stopIfTrue(x) {
if(x === true) throw "stop function"; // can be any string
}
and then:
function aFunction(){
stopIfTrue(something); // if 'something' is true an error will be thrown; function will exit
//some code
}
I would simply do this:
function checkFunction(){
return (condition);
}
function aFunction(){
if(!checkFunction()) return;
//some code
}
If what you're trying to do is this:
function aFunction()
{
if(checkFunction())
{
return;
}
//somecode
}
without using a return in aFunction(), you could do this:
function aFunction()
{
if(!checkFunction())
{
//somecode
}
}
A trick you can do is dynamically change the other function. So
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);
edit: I misread the question. This is probably way more complicated than you need.
精彩评论