我今天开始使用CoffeeScript,并(args...) => @style(args...)
在需要回调函数时发现自己使用了很多模式。上下文大致如下所示:
class Parent
@style: (feature) ->
if feature
@insight()
class Child extends Parent
@insight: ->
alert 'Sara is awesome'
@load: ->
[42].forEach((args...) => @style(args...))
Child.load()
这显示Sara is awesome
,这是准确的。如果我只使用过[42].forEach(@style)
,style
那么最终会this
引用父类(我认为呢?),而后者并不知道insight
。
但这非常冗长,我的代码中需要很多回调函数。有没有更优雅,惯用的方式来解决此问题?
(forEach
在CoffeeScript中使用这种样式是很糟糕的,但是在我的实际代码中,我正在使用各种Leaflet函数,这些函数不能仅仅用for循环来代替。)
首先要注意的是,您不应insight
从Parent
课堂上打电话。类的全部目的是提供封装。所以,我做的第一件事是将insight
要Parent
要回答您的问题,更惯用的解决方法是使用粗箭头符号。粗箭头内部执行的操作是创建一个匿名函数来封装this
。
也就是说,最终代码应如下所示:
class Parent
@style: (feature) =>
if feature
@insight()
@insight: ->
alert 'Sara is awesome'
class Child extends Parent
@load: ->
[42].forEach(@style)
Child.load()
希望能有所帮助。
编辑
根据OP注释:
class Parent
style: (feature) =>
if feature
@insight()
class Child extends Parent
load: ->
[42].forEach(@style)
insight: ->
alert 'Sara is awesome'
(new Child()).load()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句