简体   繁体   中英

Why I should use anonymous function to stored my function as variable

why this code run perfectly

function remember(number) {
    return function() {
        return number;
    }
}

const returnedFunction = remember(5);

console.log( returnedFunction() );
// 5

but this code give me error

function remember(number) {
        return number;
}

const returnedFunction = remember(5);

console.log( returnedFunction() );
// returnedFunction is not a function

In the first example, your function remember returns another function, which you then you can execute. In the second example, your function remember returns a number. That's why returnedFunction() runs fine in the first case, but throws an error in the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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