2012-08-03 27 views
0

我想用CoffeeScript创建Ruby风格的对象。所以我想要做类似CoffeeScript向构造函数发送散列参数

class A 
    constructor: (@params) -> 

a = new A {send: true, name: "fit"} 
a.send #true 

有没有什么“标准”的方法来做到这一点?

回答

1

没有办法直接做。你可以定义一个基类,有代码来做到这一点,像这样的

class Base 
    constructor: (props) -> 
     for key, value of props 
      @[key] = value 


class Extend extends Base 
    constructor: (props) -> 
     super props 
     alert "#{@key1}, #{@key2}" 


e = new Extend 'key1': 'val1', 'key2': 'val2' 


alert "#{e.key1}, #{e.key2}" 

See it working here

+0

我想过类似的东西,但我在CoffeeScript中很新,因此无法得到工作方案。谢谢。 – Ximik 2012-08-03 13:52:54