简体   繁体   English

JavaScript:所有函数都是闭包吗?

[英]JavaScript: Are all functions closures?

I know what closures are, they're functions that have access to their lexical scope, variables that would otherwise be unreachable.我知道闭包是什么,它们是可以访问其词法范围的函数,否则将无法访问的变量。

Ex:前任:

const curryMultiply = x => y => x * y;

Now, when calling curryMultiply twice, we get access to the original parameter, nothing new to the average JS developer.现在,当调用curryMultiply两次时,我们可以访问原始参数,这对普通 JS 开发人员来说并不新鲜。

But, take this example instead:但是,以这个例子代替:

const f = key => {
    return window[key];
};

Now, it doesn't create a function at all, but, it has access to the global object, so in that example, does function f have access to window via closure?现在,它根本不创建函数,但是,它可以访问全局对象,因此在该示例中,函数f是否可以通过闭包访问window

How about this:这个怎么样:

const TAU = Math.PI * 2;

export const mul_by_tau = x => x * TAU;

I know that in some languages, such as C++, these would just be functions , there's no extra thought put into it.我知道在某些语言中,例如 C++,这些只是函数,没有额外的考虑。

Previously, I had thought that global functions did not create closures, do they?以前,我认为全局函数不会创建闭包,是吗?

In Javascript, every function is a closure.在 Javascript 中,每个函数都是一个闭包。

Every function in javascript has access to lexical scope (the scope in which it is created). javascript 中的每个函数都可以访问词法范围(创建它的范围)。

Arrow functions, don't have specific functional scope.箭头函数,没有特定的功能范围。 But, they still have access to the parent scope.但是,他们仍然可以访问父作用域。

Every function's access to parent scope is through closure.每个函数对父作用域的访问都是通过闭包进行的。 If a function does not have parent function, it will have access to global scope due to closure.如果一个函数没有父函数,由于闭包,它将可以访问全局范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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