之间的功能级别范围和数据块级的范围差异 [英] Difference between function level scope and block level scope

查看:116
本文介绍了之间的功能级别范围和数据块级的范围差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在的JavaScript 被编程几个月大多采用的jQuery 。我理解的关闭并知道如何使用它们,但是我仍然无法理解什么是的的功能级别范围和数据块级的范围差异的其他语言,如< STRONG> C#。我一直在试图与这个问题没有结果自学。可能有人解释我与一些简单的例子?

I have been programming in JavaScript for a few months mostly using jQuery. I understand closures and I know how to use them, however I still can’t understand what is the difference between function level scope and block level scope in other languages such as C#. I have been trying to teach myself with no result on that subject. Could somebody explain me that with some simple examples?

推荐答案

此前ES6(当前版本的JavaScript),JavaScript的只有功能级范围。也就是说,以下内容:

Prior to ES6 (the current version of JavaScript), JavaScript had only function level scope. That is, the following:

function foo() {
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        var bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}



完全等同于:

Is exactly equivalent to:

function foo() {
    var bar;
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}



(作为事实上,我刚才显示被称为冲顶,而这正是JavaScript本身:所有变量的声明的被提升到函数的顶部;分配留他们在哪里)

(As a matter of fact, what I've just shown is called "hoisting", which is exactly what JavaScript does: all variable declarations are hoisted to the top of the function; assignments are left where they are.)

在此相反,如C#语言具有的块级别范围的。这将导致编译错误:

In contrast, languages like C# have block level scope. This would result in a compile error:

public void Foo() {
    if(true) {
        var foo = 1;
        Console.WriteLine("inside block: " + foo);
    }
    Console.WriteLine("outside block: " + foo);  // WILL NOT COMPILE
}



但你可以有这样的:

But you can have this:

public void Foo() {
    var foo = 1;
    if(true) {
        foo = 2;
        Console.WriteLine("inside block: " + foo);  // prints 2
    }
    Console.WriteLine("outside block: " + foo);     // prints 2
}

这篇关于之间的功能级别范围和数据块级的范围差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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