0

以下示例来自 Groovy in Action (2007) 一书的清单 7.22:

def boxer = new Expando()
assert null == boxer.takeThis
boxer.takeThis = 'ouch!'
assert 'ouch!' == boxer.takeThis
boxer.fightBack = {times -> return this.takeThis * times }
assert 'ouch!ouch!ouch!' == boxer.fightBack(3)

我将代码放入脚本hello.groovy中。当我运行它时,我收到以下错误:

Caught: groovy.lang.MissingPropertyException: No such property: takeThis for class: hello
groovy.lang.MissingPropertyException: No such property: takeThis for class: hello
    at hello$_run_closure1.doCall(hello.groovy:5)
    at hello.run(hello.groovy:6)

显然,第this5 行不是指boxer对象,而是指脚本。那么,将fightBack属性添加到 Expando的正确方法是什么boxer

4

1 回答 1

4

替换thisdelegate

this指的是脚本(如你所提到的),delegate指的是调用闭包的调用者。

你可以得到this,delegateowner here的用法差异。

于 2013-09-01T00:37:32.933 回答