dart 中的词法作用域是什么?

What is the Lexical Scope in dart?

基本上我正在研究闭包函数的定义,它说 -

A function that can be referenced with access to the variables in its lexical scope is called a closure

所以我想知道这个词词法范围

词法范围

词法作用域 variable/closure 等只能在定义它的代码块内访问。

Dart is a lexically scoped language. With lexical scoping, descendant scopes will access the most recently declared variable of the same name. The innermost scope is searched first, followed by a search outward through other enclosing scopes.

你可以“跟随花括号向外”来查看变量是否在范围内。

请参阅以下示例。

main() { //a new scope
  String language = "Dart";

  void outer()  {
    //curly bracket opens a child scope with inherited variables

    String level = 'one';
    String example = "scope";

    void inner() { //another child scope with inherited variables
      //the next 'level' variable has priority over previous
      //named variable in the outer scope with the same named identifier
      Map level = {'count': "Two"};
      //prints example: scope, level:two
      print('example: $example, level: $level');
      //inherited from the outermost scope: main
      print('What Language: $language');
    } //end inner scope

    inner();

    //prints example: scope, level:one
    print('example: $example, level: $level');
  } //end outer scope
  outer();
} //end main scope

词法闭包

闭包是一个函数对象,它可以访问其词法范围内的变量,即使在其原始范围之外使用该函数也是如此。

 /// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(num addBy) {
  return (num i) => addBy + i;
}

void main() {
  // Create a function that adds 2.
  var add2 = makeAdder(2);
    
  // Create a function that adds 4.
  var add4 = makeAdder(4);
    
  assert(add2(3) == 5);
  assert(add4(3) == 7);
}

您可以从 here 阅读更多内容。

Dart 是一种词法范围语言,这意味着变量的范围是静态确定的,只需通过代码的布局即可。您可以“向外跟随大括号”来查看变量是否在范围内。

下面是一个嵌套函数的例子,每个作用域级别都有变量:

String topLevel = 'Hello';

void firstFunction() {
  String secondLevel = 'Hi';
  print(topLevel);
  nestedFunction() {
    String thirdLevel = 'Howdy';
    print(topLevel);
    print(secondLevel);
    innerNestedFunction() {
      print(topLevel);
      print(secondLevel);
      print(thirdLevel);
    }
  }
  print(thirdLeve);
}

void main() => firstFunction();

这是一个有效的函数,直到最后一个打印语句。三级变量定义在嵌套函数的范围之外,因为范围仅限于它自己的块或它上面的块。