简体   繁体   English

函数作为返回类型javascript

[英]function as a return type javascript

I am trying to create a closure 我正在尝试创建一个闭包

function init(x){
     var y = 10;
     return function display(a){
        return y + a + x;
     }
     display(5);
}
init(4);

Above closure should return 19. However, it returns a function. 上面的闭包应返回19.但是,它返回一个函数。

The return is in front of the function, not the call. 返回是在函数前面,而不是调用。

function init(x){
     var y = 10;
     function display(a){
        return y + a + x;
     }
     return display(5);
}
init(4);

You have to move the "return". 你必须移动“返回”。 The return keyword will end the code execution of the function and return the value that's passed to the return (in your case a function). return关键字将结束函数的代码执行并返回传递给返回的值(在您的情况下是函数)。 If your result has to be 19, consider using the following code: 如果您的结果必须是19,请考虑使用以下代码:

function init(x) {
     var y = 10;

     function display(a) {
        return y + a + x;
     }

     return display(5);
}

init(4);

The last line in your init function is unreachable , once it's after a return statement. 一旦返回语句之后,init函数中的最后一行是无法访问的。 If you want to return a primitive value, you have to return the result of the display function. 如果要返回原始值,则必须返回显示函数的结果。

function init(x){
     var y = 10;
     function display(a){
        return y + a + x;
     }
     return display(5);
}
init(4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM