Can someone explain to me how this function works?

妖精的绣舞 提交于 2019-12-07 07:49:48

问题


I'm learning to code and I'm trying to understand Higher Order Functions and abstractions. I don't understand how this piece of code runs to return "true".

function greaterThan(n) {
  return function(m) { return m > n; };
}

var greaterThan10 = greaterThan(10);

console.log(greaterThan10(11));

Thanks for the help.


回答1:


The function greaterThan returns a function when called. The returned function has access to all the members of the outer function even after the function has returned. This is called closure.

function greaterThan(n) {
    return function (m) {
        return m > n;
    };
}

When following statement is executed

var greaterThan10 = greaterThan(10);

it is converted as

var greaterThan10 = function (m) {
    return m > 10;
};

So, greaterThan10 is now the function and can be called as

console.log(greaterThan10(11));

Now, value of m is 11 and return 11 > 10; returns as true.

Read more about closures:

How do JavaScript closures work?

Also, I'll recommend following great article to all the JS developers

http://dmitryfrank.com/articles/js_closures



来源:https://stackoverflow.com/questions/32753388/can-someone-explain-to-me-how-this-function-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!