静态类和方法在coffeescript [英] Static classes and methods in coffeescript

查看:159
本文介绍了静态类和方法在coffeescript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在coffeescript中写一个静态辅助类。这是否可能?



class:

  Box2DUtility 

constructor:() - >

drawWorld:(world,context) - >

使用:

 code> Box2DUtility.drawWorld(w,c); 


解决方案

c $ c> @ :

  class Box2DUtility 
constructor:() - >
@drawWorld:(world,context) - >警告'世界画!'

#然后画出你的世界...
Box2DUtility.drawWorld()

演示: http://jsfiddle.net/ambiguous/5yPh7/ p>

如果你想让 drawWorld 作为一个构造函数,你可以说 new @ 这样:

  class Box2DUtility 
constructor:(s) - > @s = s
m:() - > alert实例方法调用:#{@ s}
@drawWorld:(s) - > new @ s

Box2DUtility.drawWorld('pancakes')。m()

演示: http://jsfiddle.net/ambiguous/bjPds/1/


I want to write a static helper class in coffeescript. Is this possible?

class:

class Box2DUtility

  constructor: () ->

  drawWorld: (world, context) ->

using:

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()

Demo: http://jsfiddle.net/ambiguous/5yPh7/

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()

Demo: http://jsfiddle.net/ambiguous/bjPds/1/

这篇关于静态类和方法在coffeescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆