以下示例来自 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)
显然,第this
5 行不是指boxer
对象,而是指脚本。那么,将fightBack
属性添加到 Expando的正确方法是什么boxer
?