coffeescript 中的静态类和方法 [英] Static classes and methods in coffeescript
本文介绍了coffeescript 中的静态类和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在coffeescript 中编写一个静态助手类.这可能吗?
I want to write a static helper class in coffeescript. Is this possible?
类:
class Box2DUtility
constructor: () ->
drawWorld: (world, context) ->
使用:
Box2DUtility.drawWorld(w,c);
推荐答案
您可以通过在类方法前加上 @
来定义它们:
You can define class methods by prefixing them with @
:
class Box2DUtility
constructor: () ->
@drawWorld: (world, context) -> alert 'World drawn!'
# And then draw your world...
Box2DUtility.drawWorld()
演示:http://jsfiddle.net/ambiguous/5yPh7/
如果你想让你的 drawWorld
像构造函数一样工作,那么你可以这样说 new @
:
And if you want your drawWorld
to act like a constructor then you can say new @
like this:
class Box2DUtility
constructor: (s) -> @s = s
m: () -> alert "instance method called: #{@s}"
@drawWorld: (s) -> new @ s
Box2DUtility.drawWorld('pancakes').m()
演示:http://jsfiddle.net/ambiguous/bjPds/1/
这篇关于coffeescript 中的静态类和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文