有人可以向我解释此功能的工作原理吗?
我正在学习编码,并且试图理解高阶函数和抽象。我不明白这段代码是如何运行的,以返回 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
在调用时返回一个函数。即使在函数返回之后,返回的函数也可以访问外部函数的所有成员。这称为 关闭
。
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
和返回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