简体   繁体   中英

Can someone explain to me how this code works? Closure in Dart

I can't understand how the closure works in Dart. Why does BMW stay? This explanation causes my neurons to overheat. A lexical closure is a functional object that has access to variables from its lexical domain. Even if it is used outside of its original scope.

 `void main() {
  var car = makeCar('BMW');
  print(makeCar);
  print(car);
  print(makeCar('Tesla'));
  print(car('Audi'));
  print(car('Nissan'));
  print(car('Toyota'));
 }

 String Function(String) makeCar(String make) {
 var ingane = '4.4';
 return (model) => '$model,$ingane,$make';
 }`

Console

Closure 'makeCar'
Closure 'makeCar_closure'
Closure 'makeCar_closure'
Audi,4.4,BMW
Nissan,4.4,BMW
Toyota,4.4,BMW

Calling car('Audi') is equal to calling (makeCar('BMW'))('Audi');

A lexical closure is a functional object that has access to variables from its lexical domain. Even if it is used outside of its original scope.

in simple english:

String make will stay valid as long as the returned function is not out of scope because the returned function has reference to String make .

In essence, you "inject" information needed for the newly created function. Your car knows that make is "BMW"

I think I figured it out. Here is an example where I left comments. Maybe it will help someone.

void main() {
  var pr = funkOut(10); // assign a reference to an object instance
  // of the Function class to the pr variable. pr is a closure because
  // it is assigned a reference to an instance that contains a lexical
  // environment (int a) and an anonymous function from this environment.
  // 10  transfer to a
  print(pr(5)); // 5 transfer to b //15
  print(pr(10)); // 10 transfer to b //20
  pr = funkOut(20);// 20 transfer to a
  print(pr(5)); // 5 transfer to b //25
  print(pr); // Closure: (int) => int
}

Function funkOut(int a) {
  return (int b) => a + b;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM