簡體   English   中英

如何在javascript箭頭函數中返回嵌套函數的結果?

[英]How to return result of the nested function in javascript arrow function?

無法弄清楚如何在箭頭函數中返回嵌套函數的結果。

如何表達這個(工作正常):

var stopEating = (function() {
    var loadedStomach = false;
    return function() {
        if(!loadedStomach){
            loadedStomach = true;
            console.log('Stop eating');
        }};
})();

作為箭頭函數(無法正常工作):

const stopEating = () => {
    let loadedStomach = false;
    return () => {
        if(!loadedStomach) {
            loadedStomach = true;
            console.log('Its enough eating!');
        }};
};

您需要調用該函數才能獲得結果,因此,在末尾添加括號。

const stopEating = (() => {
    let loadedStomach = false;
    return () => {
        if(!loadedStomach) {
            loadedStomach = true;
            console.log('Its enough eating!');
        }
    };
})();

在第一個示例中,您創建了立即調用函數表達式 (IIFE)

它是一個 JavaScript 函數,一定義就運行。 這就是為什么您會收到內部函數,該函數會打印“停止進食”。

要實現這種模式,您只需要包裝箭頭函數:

const stopEating = (() => {
    let loadedStomach = false;
    return () => {
        if(!loadedStomach) {
            loadedStomach = true;
            console.log('Its enough eating!');
        }
    };
})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM