这是一个关闭吗?如果是这样,为什么?

发布于 2024-10-14 02:24:09 字数 1055 浏览 3 评论 0原文

在准备回答另一个问题时,我为自己创建了一个问题。考虑以下短节目。

(ns net.dneclark.JFrameAndTimerDemo
  (:import (javax.swing JLabel JButton JPanel JFrame Timer))
  (:gen-class))

(defn timer-action [label counter]
 (proxy [java.awt.event.ActionListener] []
   (actionPerformed
     [e]
      (.setText label (str "Counter: " (swap! counter inc))))))

(defn timer-fn []
  (let [counter (atom 0)
        label (JLabel. "Counter: 0")
        timer (Timer. 1000 (timer-action label counter))
        panel (doto (JPanel.)
                (.add label))]
    (.start timer)
    (doto (JFrame. "Timer App")
      (.setContentPane panel)
      (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
      (.setLocation 300 300)
      (.setSize 200 200)
      (.setVisible true))))

(defn -main []
  (timer-fn))

在动作监听器“timer-action”中,“counter”参数的值被更改。实际变量在“timer-fn”函数中声明,但在侦听器中更改。根据我早期使用 Pascal 等语言的经验,我认为“计数器”是通过引用传递的。这是这里的情况还是这是一个闭包的例子?还有别的事吗?

感谢您的帮助。

While preparing an answer to another question, I created one for myself. Consider the following short program.

(ns net.dneclark.JFrameAndTimerDemo
  (:import (javax.swing JLabel JButton JPanel JFrame Timer))
  (:gen-class))

(defn timer-action [label counter]
 (proxy [java.awt.event.ActionListener] []
   (actionPerformed
     [e]
      (.setText label (str "Counter: " (swap! counter inc))))))

(defn timer-fn []
  (let [counter (atom 0)
        label (JLabel. "Counter: 0")
        timer (Timer. 1000 (timer-action label counter))
        panel (doto (JPanel.)
                (.add label))]
    (.start timer)
    (doto (JFrame. "Timer App")
      (.setContentPane panel)
      (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
      (.setLocation 300 300)
      (.setSize 200 200)
      (.setVisible true))))

(defn -main []
  (timer-fn))

In the action listener, 'timer-action', the value of the 'counter' argument is altered. The actual variable is declared in the 'timer-fn' function, but is altered in the listener. In my earlier experience with languages like Pascal, I would have considered 'counter' to be passed by reference. Is that the case here or is this an example of a closure? Something else?

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵情客 2024-10-21 02:24:09

是的,这是一个关闭。处理函数定义的词法上下文被保留,当稍后调用它时,它可以访问和更新“存在”在那里的变量。

我不知道如何回答这个问题:“为什么?”除了指出这只是语言定义的工作方式之外。

Yes, it's a closure. The lexical context of the handler function definition is preserved, and when it is later invoked it can access and update variables that "live" there.

I'm not sure how to answer the question, "why?" other than to point out that it's simply the way the language is defined to work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文