範例在這邊:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; < lexical binding example > | |
;; lexical binding makes it easy to see at a glance what the dependencies are. | |
(defn circle-area [radius] | |
(* Math/PI (* radius radius))) | |
(circle-area 10.0) | |
;=> 314.1592653589793 | |
;; < dynamic binding example > | |
;; dynamic binding is useful when it would be too cumbersome to pass values through | |
;; a chain of functions that are otherwise oblivious to the value some lower-level function needs. | |
(declare ^:dynamic *radius*) | |
(defn circle-area [] | |
(* Math/PI (* *radius* *radius*))) | |
(binding [*radius* 10.0] | |
(circle-area)) | |
; => 314.1592653589793 |
javascript 的變數是採用 lexical binding 。但是, this 這個變數會隨著程式的運行,而指向不同的物件,this 顯然就是 dynamic binding 的變數。甚至 javascript 也提供了 bind 函數,可以用來明確地將函數與某個特定的物件做綁定。
有一種說法: 「Javascript 也可以算是一種 Lisp 的方言」。算不算是,自然是見仁見智。然而,如果我們從這個 lexical binding 和 dynamic binding 的角度來切入的話,確實是有特別的相似之處:因為都同時支持了兩種綁定方式。