有人可以向我解释此功能的工作原理吗? [英] Can someone explain to me how this function works?

查看:99
本文介绍了有人可以向我解释此功能的工作原理吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习编码,并且试图理解高阶函数和抽象。我不明白这段代码是如何运行的,以返回 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:

JavaScript闭包如何工作?

此外,我建议向所有JS开发人员推荐以下出色的文章

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

http://dmitryfrank.com/articles/js_closures

这篇关于有人可以向我解释此功能的工作原理吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆