以下示例来自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
的正确方法是什么?
答案 0 :(得分:4)