词法范围:
它是在各种编程语言中使用的术语(不仅仅是在dart),用于描述当控件超出存在范围的代码块时变量范围不存在的情况。 Dart是一种词法作用域语言,即您可以通过大括号找到变量的作用域。
示例 1:变量的词法作用域。
// Declaring a variable whose scope is global
var outter_most;
void main() {
// This variable is inside main and can be accessed within
var inside_main;
void geeksforgeeks() {
// This variable is inside geeksforgeeks and can be accessed within
var inside_geeksforgeeks;
void geek() {
// This variable is geek and can be accessed within
var inside_geek;
}
}
}
The above code depicts, about the scope of the variable in dart function and how their scope
ends outside braces.
词法闭包:
在编程语言中的词汇关闭,也被称为闭合或闭合函数,是实现词法范围的名字在函数结合的方式。它是一个函数对象,可以访问其词法范围内的变量,即使在该范围外使用该函数也是如此。
示例 2:
Function geeksforgeeks(num add) {
return (num i) => add + i;
}
void main() {
// Create a function that adds 2.
var geek1 = geeksforgeeks(2);
// Create a function that adds 4.
var geek2 = geeksforgeeks(4);
print(geek1(3));
print(geek2(3));
}
输出:
5
7
Note:
Functions can close over variables defined in surrounding scopes. In the following example,
geeksforgeeks() captures the variable addBy. Wherever the returned function goes, it remembers
"add" variable.