Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Closure

JavaScript Closure

Ping-Yen Tsai

May 14, 2014
Tweet

More Decks by Ping-Yen Tsai

Other Decks in Technology

Transcript

  1. JavaScript 函式裡還可以宣告函式 f u n c t i o n

    f ( ) { g ( ) ; f u n c t i o n g ( ) { a l e r t ( 1 ) ; } } f ( ) ; / / 1 g ( ) ; / / R e f e r e n c e E r r o r : g i s n o t d e f i n e d 2 / 10
  2. 裡面的函示可以存取外面函示的變數 f ( ) ; f u n c t

    i o n f ( ) { v a r c = 0 ; g ( ) ; a l e r t ( c ) ; / / 1 g ( ) ; a l e r t ( c ) ; / / 2 f u n c t i o n g ( ) { + + c ; } } 3 / 10
  3. Closure = 函式 + 函式外變數 f u n c t

    i o n f ( ) { v a r c = 0 ; f u n c t i o n g ( ) { + + c ; } } 函式與函式外變數生存期間一致 v a r h = f ( ) ; f u n c t i o n f ( ) { v a r c = 0 ; f u n c t i o n g ( ) { + + c ; } r e t u r n g ; } 4 / 10
  4. Closure Sample v a r h 1 = f (

    ) ; h 2 = f ( ) ; h 1 ( ) ; / / 1 h 1 ( ) ; / / 2 h 2 ( ) ; / / 1 f u n c t i o n f ( ) { v a r c = 0 ; f u n c t i o n g ( ) { a l e r t ( + + c ) ; } r e t u r n g ; } 5 / 10
  5. Closure Sample v a r h = ( f u

    n c t i o n ( ) { v a r c = 0 ; r e t u r n f u n c t i o n ( ) { + + c ; } } ) ( ) ; 6 / 10
  6. Global 變數 v a r c = 0 ; v

    a r h = f u n c t i o n ( ) { a l e r t ( + + c ) ; } ; h ( ) ; / / 1 h ( ) ; / / 2 h ( ) ; / / 3 Closure v a r h = ( f u n c t i o n ( ) { v a r c = 0 ; r e t u r n f u n c t i o n ( ) { a l e r t ( + + c ) ; } ; } ) ( ) ; h ( ) ; / / 1 h ( ) ; / / 2 h ( ) ; / / 3 7 / 10