Let a function “return” the super function?

烂漫一生 提交于 2019-12-23 17:27:24

问题


Given is the following code:

function two() {
    return "success";
}

function one() {
    two();
    return "fail";
}

If you test the code by calling function one(), you will always get "fail".

The question is, how can I return "success" in function one() by only calling function two()?

Is that even possible?

Regards


回答1:


You can't make a function return from the function that called it in Javascript (or many other languages, afaik). You need logic in one() to do it. E.g.:

 function one() {
     return two() || "fail";
 }



回答2:


function one() {
   return two();
}



回答3:


You could do it, using a try-catch Block, if your function one anticipates a probable non-local-return as well as function two like this using exceptions:

function two() {
  throw {isReturn : true, returnValue : "success"}
}


function one () {
  try {
    two()
  } catch(e) {
    if(e.isReturn) return e.returnValue;
  }
  return "fail";
 }

, I believe.




回答4:


function one() {    
    return two();
}


来源:https://stackoverflow.com/questions/3923920/let-a-function-return-the-super-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!