0

在 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? ###
4

2 回答 2

1

做到这一点的唯一方法是引用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构造它的概念(如果有的话就没有意义了);你必须明确表示。

于 2013-02-23T23:15:42.503 回答
0

您需要引用另一个类的实例,例如

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) ->
于 2013-02-23T23:19:18.877 回答