有人可以向我解释这个功能是如何工作的吗?
我正在学习编码,我正在尝试理解高阶函数和抽象.我不明白这段代码如何运行以返回true".
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));
感谢您的帮助.
greaterThan
函数在调用时返回一个函数.即使在函数返回之后,返回的函数也可以访问外部函数的所有成员.这称为closure
.
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;
};
}
执行以下语句时
var greaterThan10 = greaterThan(10);
转换为
var greaterThan10 = function (m) {
return m > 10;
};
所以,greaterThan10
现在是函数,可以调用为
So, greaterThan10
is now the function and can be called as
console.log(greaterThan10(11));
现在,m
的值为 11
并且 return 11 >10;
返回为 true
.
Now, value of m
is 11
and return 11 > 10;
returns as true
.
阅读有关闭包的更多信息:
Read more about closures:
另外,我会向所有 JS 开发人员推荐以下好文章
Also, I'll recommend following great article to all the JS developers