我怎样才能在javascript中使用return

far*_*oft 7 javascript return function

我怎样才能在javascript中使用return

function hello1() {

    function hello2() {

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

    }

}
Run Code Online (Sandbox Code Playgroud)

Cam*_*ron 15

你不能.这不是可行的方式return.它仅从当前函数退出.

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

你可能想要的是这样的:

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

    if (!hello2()) {
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)