在 CoffeeScript 中,我如何从另一个类调用一个类方法,以便两个类实例都存储在第三个类中?
示范:
class A
constructor: () ->
@b = new B
@c = new C
class B
methodB: () ->
class C
methodC: () ->
### How would I call instance b's methodB from here? ###
在 CoffeeScript 中,我如何从另一个类调用一个类方法,以便两个类实例都存储在第三个类中?
示范:
class A
constructor: () ->
@b = new B
@c = new C
class B
methodB: () ->
class C
methodC: () ->
### How would I call instance b's methodB from here? ###
做到这一点的唯一方法是引用A
类的实例。例如,如果我了解您要正确执行的操作:
class A
constructor: () ->
@b = new B
@c = new C(this)
class B
methodB: () ->
class C
constructor (@parent) ->
methodC: () ->
@parent.b.methodB()
的实例C
不知道它的实例A
有对它的引用——没有内置的c
“属于”a
构造它的概念(如果有的话就没有意义了);你必须明确表示。
您需要引用另一个类的实例,例如
class A
constructor: () ->
@b = new B
@c = new C
@c.setB(@b)
@c.methodC() # Also calls B.methodB()
class B
methodB: () ->
class C
methodC: () ->
@b.methodB()
setB: (@b) ->