Javascript中存在什么类型的范围? [英] What types of scope exist in Javascript?

查看:139
本文介绍了Javascript中存在什么类型的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有全局范围以及可嵌套的功能范围。但是在Javascript中还有其他类型的作用域或者闭包吗?

I understand that there is global scope, and additionally nestable functional scope. But are there any other types of scopes or closures in Javascript?

当我们讨论这个话题时,作用域和闭包有什么区别?

While we're on the topic, what's the difference between a scope, and a closure?

推荐答案

闭包是一堆可见的范围。让我们假设您有以下代码:

A closure is a stack of visible scopes. Let's say you have the following code:

var v1;
function a() {
    var v2;
    function b() {
        var v3;
        function c() {
            var v4;
        }
        return c;
    }
    return b();
}
var f = a();

c 范围(其中 v4 被定义), b 函数的作用域(其中定义了 a 函数的范围(其中定义了 v2 ),定义了全局范围( v1 )。可见范围的堆栈是闭包,函数绑定到该闭包。当引用 c 函数返回调用链时,从 b a ,最后赋给 f ,它带有这个闭包绑定,所以当你调用 f(),它将可以访问所有这些范围,即使你看起来在全局范围中调用一个函数。正如你所看到的,只有两种范围 - 全局作用域和函数作用域。主要的区别是,全局作用域中的变量被定义为全局对象的属性,而函数作用域var不是任何对象的属性,不能以任何其他方式引用,而是通过名称引用。闭包本身不是作用域,而是作用域的集合。

c is a function that has 4 visible scopes: its own scope (where v4 is defined), the b function's scope (where v3 is defined), the a function's scope (where v2 is defined), and the global scope (where v1 is defined). That stack of visible scopes is the closure, and the function is bound to that closure. When the reference to the c function is returned up the call chain, from b to a and finally assigned to f, it carries this closure binding with it, so when you invoke f(), it will have access to all those scopes, even though you're seemingly invoking a function in the global scope. As you see, there are only two kinds of scopes involved — the global scope and the function scope. The main difference is that variables in the global scope are defined as properties of the global object, while function scope vars are not properties of any object and cannot be referenced in any other way but by name. A closure is not a scope in itself, but a collection of scopes.

这篇关于Javascript中存在什么类型的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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