使用JavaScript,使其使用闭包来返回响应



我正在尝试实现下面的JavaScript代码,因此它使用闭包来返回响应

(function() {
function hello(name, age) {
return name + ", who is " + age + " years old, says hi!"); 
}
console.log(hello('John', 33)); 
}();

您发布的代码是一个自执行匿名函数,而不是闭包。事实上,代码中根本没有闭包,因为没有变量的作用域跨越函数边界。

如果您想从SEAF返回一个值,只需添加一个return语句:

const message = (function() {
function hello(name, age) {
return name + ", who is " + age + " years old, says hi!"; 
}
const result = hello('John', 33);
console.log( result ); 
return result;
}();

如果您想通过SEAF将hello函数导出为一个没有任何参数的新函数(因为参数是在返回的lambda中捕获的,即Partial Application的一个示例,请执行以下操作:

const hello = (function() {
function hello(name, age) {
return name + ", who is " + age + " years old, says hi!"; 
}
return () => hello('John', 33);
}());
console.log( hello() ); // will print  "John, who is 33 years old, says hi!" to the console.

最新更新