全球还是关闭? [英] Global or Closure?

查看:92
本文介绍了全球还是关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解变量'a'是一个全局变量。但是当我在Chrome控制台中检查这个时,我发现变量'a'是一个闭包。为什么?

As per my understanding variable 'a' is a global variable. But when I check this in Chrome console, I find variable 'a' as a closure. Why?

var a = 5;
function abc()
{
 var b = 4;
 return a*b;
}
console.dir(abc);


推荐答案

是的,它在Chrome中显示但在Mozilla中没有显示。

Yes it shows in Chrome but not in Mozilla.

首先,您需要了解JavaScript中的词法作用域。这意味着内部函数可以访问其父作用域的变量和其他资源。这里父作用域是全局作用域。

First you need to understand lexical scoping in JavaScript. It means that the inner functions have access to the variables and other resources of their parent scope. Here the parent scope is global scope.

这是函数如何使用闭包在函数内部添加一个定义的变量。为了执行该函数,它将查找它需要的变量。变量'a'未在内部定义,因此它将查看函数外的范围,直到找到它为止。

This is how the function adds a variable defined outside the function, inside it using closure. In order to execute the function, it will look for the variables it need. Variable 'a' in not defined inside so it will look at scope outside the function till it finds it.

这是一个闭包。

这篇关于全球还是关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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