[FUNC]用ahk的类实现秒表

来源:互联网 发布:java方法是什么意思 编辑:程序博客网 时间:2024/06/05 06:59
; 示例 #4: 使用 method 作为定时器子程序.counter := new SecondCountercounter.Start()Sleep 5000counter.Stop()Sleep 2000; 一个记录秒数的示例类...class SecondCounter {    __New() {        this.interval := 1000        this.count := 0        ; Tick() 有一个隐式参数 "this" 引用一个对象        ; 所以        ; 我们需要创建一个封装 "this" 和 Tick 方法的函数来调用:        this.timer := ObjBindMethod(this, "Tick")    }    Start() {        ; 已知限制: SetTimer 需要一个纯变量引用.        timer := this.timer        SetTimer % timer, % this.interval        ToolTip % "Counter started"    }    Stop() {        ; 在此之前传递一个相同的对象来关闭定时器:        timer := this.timer        SetTimer % timer, Off        ToolTip % "Counter stopped at " this.count    }    ; 本例中,定时器调用了以下方法:    Tick() {        ToolTip % ++this.count    }} 

备注:

  • 我们也可使用 this.timer := this.Tick.Bind(this). 当this.timer 被调用时, 它实际上是调用 this.Tick.Call(this) 元方法 (除非this.Tick 没有再次执行). 而 ObjBindMethod 则是创建了一个调用this.Tick() 的对象.
  • 如果我们将 Tick 更名为 Call, 可直接使用 this 而非 this.timer. 这样也不会产生临时变量. 但 ObjBindMethod 在对象拥有多个可被不同事件源触发的方法时会很有用, 如热键, 菜单项, GUI控件等.
  • 如果定时器被自身调用的 函数/方法 修改或删除时, 它可能会简单的 忽略 Label 参数. 在某些情况下,这样就避免了需要保留原始对象传递给定时器, 这样可以省略一个临时变量 (就像上面例子中的timer 那样).