Javascript 在多个函数后返回真/假
所以我要问的是,在这个场景中,原始的Javascript 在多个函数后返回真/假,javascript,Javascript,所以我要问的是,在这个场景中,原始的checkUserRole()会被认为是正确的吗?或者我是否需要将true从anotherFunction()传递到checkUserRole()?否,您需要显式返回它: function topFunction() { if (checkUserRole()) { //trying to figure out if I will hit this line } } checkUserRole() { anotherFunction()
checkUserRole()
会被认为是正确的吗?或者我是否需要将true
从anotherFunction()
传递到checkUserRole()
?否,您需要显式返回它:
function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
anotherFunction()
}
anotherFunction() {
return true;
}
如果在
checkUserRole
函数中没有返回,则从另一个函数返回的true
将丢失。您最初编写它的方式不会从checkUserRole
返回任何内容,这意味着它将无法通过“truthy”在topFunction
中的if语句中进行测试,无论anotherFunction
或checkUserRole
中发生什么情况,您都缺少checkUserRole方法中的return语句checkUserRole()
将调用anotherFunction
但不返回任何值,因此,它将隐式返回undefined
,这是错误的,因此不会进入if
正文。return
语句不会跨越函数边界。否则函数的调用者在不知道被调用者的实现的情况下无法知道发生了什么。谢谢,这是我在寻找另一个相关问题的内容,您是否可以在此基础上添加另一个函数?因此,您将返回另一个函数(),然后在下面返回yetAnotherFunction(),以便找到真/假?您当然可以,看看下面的:
function topFunction() {
if (checkUserRole()) {
//trying to figure out if I will hit this line
}
}
checkUserRole() {
return anotherFunction();
}
anotherFunction() {
return true;
}