下面的示例来自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的正确方法是什么?
发布于 2013-09-01 00:37:32
将this替换为delegate。
this指的是脚本(正如您提到的),delegate是指调用闭包的调用方。
您可以得到this、delegate和owner 这里的用法差异。
https://stackoverflow.com/questions/18553939
复制相似问题