如何在JavaScript中使用返回值 [英] How can I use return in javascript

查看:134
本文介绍了如何在JavaScript中使用返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数hello1(){

函数hello2( ){

if(condition){
return; //如何退出hello1函数而不是hello2?
}

}

}


解决方案

你不能。这不是 return 的工作方式。它仅从当前函数退出。



能够从函数进一步返回调用堆栈将会破坏封装(即它不应该知道它从哪里被调用,它应该由调用者决定要做什么如果该功能失败)。函数的一部分是调用者不需要知道函数是如何实现的。



你可能想要的是这样的:

 函数hello1(){
函数hello2(){
if(condition){
return false ;
}
返回true;
}

if(!hello2()){
return;
}
}


How can I use return in javascript

function hello1() {

    function hello2() {

        if (condition) {
            return; // How can I exit from hello1 function not hello2 ?
        }

    }

}

解决方案

You can't. That's not the way return works. It exits only from the current function.

Being able to return from a function further up the call stack would break the encapsulation offered by the function (i.e. it shouldn't need to know where it's being called from, and it should be up to the caller to decide what to do if the function fails). Part of the point of a function is that the caller doesn't need to know how the function is implemented.

What you probably want is something like this:

function hello1() {
    function hello2() {
        if (condition) {
            return false;
        }
        return true;
    }

    if (!hello2()) {
        return;
    }
}

这篇关于如何在JavaScript中使用返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆