[英]How to return result of the nested function in javascript arrow function?
Can't figure out how to return result of the nested function in arrow function.无法弄清楚如何在箭头函数中返回嵌套函数的结果。
How to express this one (works fine):如何表达这个(工作正常):
var stopEating = (function() {
var loadedStomach = false;
return function() {
if(!loadedStomach){
loadedStomach = true;
console.log('Stop eating');
}};
})();
as an arrow function (doesn't work properly):作为箭头函数(无法正常工作):
const stopEating = () => {
let loadedStomach = false;
return () => {
if(!loadedStomach) {
loadedStomach = true;
console.log('Its enough eating!');
}};
};
You need to call the function in order to get the results, thus, adding the parentheses at the end.您需要调用该函数才能获得结果,因此,在末尾添加括号。
const stopEating = (() => {
let loadedStomach = false;
return () => {
if(!loadedStomach) {
loadedStomach = true;
console.log('Its enough eating!');
}
};
})();
Into the first example, you created Immediately Invoked Function Expression (IIFE) .在第一个示例中,您创建了立即调用函数表达式 (IIFE) 。
It's a JavaScript function that runs as soon as it is defined.它是一个 JavaScript 函数,一定义就运行。 That's why you receive internal function, which prints "Stop Eating".
这就是为什么您会收到内部函数,该函数会打印“停止进食”。
To realize this pattern you just need to wrap arrow function:要实现这种模式,您只需要包装箭头函数:
const stopEating = (() => {
let loadedStomach = false;
return () => {
if(!loadedStomach) {
loadedStomach = true;
console.log('Its enough eating!');
}
};
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.