2015-06-14 56 views
0

之间实例我有4个的CoffeeScript类,如下所示:共享两个其它类

class Main 
    constructor: (element) -> 
    @element = $(element) 
    @one = new One() 
    @two = new Two(@one) 
    @dummy = new Dummy(@one, @two) 

class One 
    constructor: (class_two_instance) -> 
    # do something 

class Two 
    constructor: (class_one_instance) -> 
    # do something 

class Dummy 
    constructor: (class_one_instance, class_two_instance) 
    # do something 
jQuery -> 
    new Main($("#main")) 

我需要的类One和类Two到所有其它(实际的或未来的)类之间共享。

我开始做的是将它们作为参数传递,你可以在Main

@dummy = new Dummy(@one, @two) 

看到,但该类One我只需要通过@two。该类Two我只需要同样的事情通过@one

不幸的是它似乎无法做到这一点的同时,你可以看到(我无法通过@two作为参数new One()):

@one = new One() 
@two = new Two(@one) 

有没有办法解决这个问题?

+0

这听起来像你不想要一个“阶级”在所有的这些。只是对象。 –

+0

@ T.J.Crowder你的意思是什么? – medBo

+0

听起来像一个和两个只应该是对象,而不是类,如果你只有一个人想要它们。 –

回答

1

这听起来我好像onetwo不应该在所有类,只是单个对象:

one = { 
    data: "I'm one", 
    method:() -> 
    # do something 
    # if needed, you can use two here 
} 
two = { 
    data: "I'm two", 
    method:() -> 
    # do something else 
    # if needed, you can use one here 
} 
class Main 
    constructor: (element) -> 
    @element = $(element) 
    @dummy = new Dummy() 
    # if needed, you can use one and two here 

class Dummy 
    constructor:() -> 
    # do something 
    # if needed, you can use one and two here 

jQuery -> 
    new Main($("#main")) 
+0

我最终通过改变我的代码的写法,但你的答案是完全正确的..所以我接受它。谢谢你,兄弟。 – medBo

0

您可以将它们作为原型对象传递。

Dummy.prototype = Object.create(Two.prototype);

那么你可以做同样的事情二级和设置它的原型之一。

Two.prototype = Object.create(One.prototype);

现在虚拟实例都可以访问到已经宣布一类和二班的样机所有功能和特性。

正如你所看到的这种模式的工作,你需要定义所有的公众在一个和两个原型的方法和属性。