简体   繁体   English

如何在javascript箭头函数中返回嵌套函数的结果?

[英]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.

相关问题 如何在JavaScript中将箭头函数(=>)的结果分配给变量 - How to assign a result of an arrow function (=>) to a variable in JavaScript JavaScript嵌套function使用addListener时如何返回结果? - How to return result of nested function in JavaScript when using addListener? 如何在 javascript 中返回嵌套的 function? - How to return nested function in javascript? 箭头函数返回函数文本而不是结果(javascript) - arrow function returns the function text and not the result (javascript) 如何在 function 中使用引用嵌套 function 内部参数的条件语句在 javascript 中返回结果? - How can use a conditional statement inside of a function that references the parameter inside of a nested function to return a result in javascript? 操作后JavaScript嵌套的异步函数返回结果 - JavaScript nested async function return result after manipulation 如何返回结果值 out 函数 JavaScript - How to return result value out function JavaScript 如何返回onclick函数是javascript中href的结果? - How to return the onclick function is result to href in javascript? 如何在phonegap javascript函数中返回结果? - how to return result in phonegap javascript function? (JavaScript) 如何从另一个 function 返回结果? - (JavaScript) How to return result from another function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM