添加新属性时请参阅Expando对象?

时间:2013-09-01 00:00:46

标签: groovy

以下示例来自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)

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

1 个答案:

答案 0 :(得分:4)

this替换为delegate

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

您可以区分thisdelegateowner here的使用情况。