Belajar Bahasa Pemrograman Dart : Closures

Dhe997

Closures

Suatu fungsi dapat dibuat dalam lingkup global atau di dalam fungsi lain. Suatu fungsi yang dapat mengakses variabel di dalam lexical scope-nya disebut dengan closure

Lexical scope berarti bahwa pada sebuah fungsi bersarang (nested functions), fungsi yang berada di dalam memiliki akses ke variabel di lingkup induknya.
Berikut ini adalah contoh kode implementasi closure:


  1. void main() {

  2.   var closureExample = calculate(2);

  3.   closureExample();

  4.   closureExample();

  5. }

  6.  

  7. Function calculate(base) {

  8.   var count = 1;

  9.  

  10.   return () => print("Value is ${base + count++}");

  11. }



Ketika kode di atas dijalankan, konsol akan tampil seperti berikut:


  1. Value is 3

  2. Value is 4



Di dalam fungsi calculate() terdapat variabel count dan mengembalikan nilai berupa fungsi. 
Fungsi lambda di dalamnya memiliki akses ke variabel count karena berada pada lingkup yang sama. 
Karena variabel count berada pada scope calculate, maka umumnya variabel tersebut akan hilang atau dihapus ketika fungsinya selesai dijalankan. Namun pada kasus di atas fungsi lambda atau closureExample masih memiliki referensi atau akses ke variabel count sehingga bisa diubah. Variabel pada mekanisme di atas telah tertutup (close covered), yang berarti variabel tersebut berada di dalam closure

Posting Komentar

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.