I need to override some behaviour of function, that goes after it calls other function. The problem is that this parent function is a library and I dont want to change it, so solutions like make some flag or another change of this function is not so good. I know that I got an caller object in function that I can change, so maybe I can figure out smth with it. Heres the example:
function parent()
{
console.log("some need stuff");
some.handler.function.from.config.that.i.can.change();
console.log("need omit this right till the end");
}
function child()
{
console.log("need to somehow stop evaluation of " + child.caller + " function");
}
As a ruby programmer I know there is lambdas with which you can terminate evaluation from inner scope of closure. But Im not sure how to do this from javascript.
You can't do that directly. (Moreover .caller is obsolete)
You can however use a dirty trick:
try{
parentFunction();//calls child
}catch(e){
//done
}
function child(){
doWhatever();
throw new Error("this will hopefully propagate");
}
This will only work assuming the parent does not catch exceptions itself when calling the child.
Moreover, it is generally a bad idea to use exceptions for flow control. Use this as a last resort.
Call a new function that you do control before you call the library, and wrap the call to the library you cannot modify in a try/catch block.
For example:
function meta-parent()
{
try {
parent();
}
catch (e){
// don't really be empty!
}
}
function parent()
{
console.log("some need stuff");
some.handler.function.from.config.that.i.can.change();
// Nothing below here will run because of your child's exception
console.log("need omit this right till the end");
}
function child()
{
console.log("need to somehow stop evaluation of " + child.caller + " function");
throw new Error(); //breakout!
}
Note inspiration: Breaking a parent function from within a child function (PHP Preferrably)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With