调用方法并在Coffeescript中传递适当的上下文

时间:2015-12-29 13:17:44

标签: javascript class coffeescript

这是我class的简化版本:

class Calculations
  constructor: (amount = 1000) ->
    @amount = amount

  rowOne: =>
    columnOne:   => @amount * 0.1
    columnTwo:   => @amount * 0.2
    columnThree: => @amount * 0.3
    total:       => @_total(context)

  _total: (context) ->
    context.columnOne() + context.columnTwo() + context.columnThree()

我想调用这样的方法:

calc = new Calculations()

calc.rowOne().columnOne()    # And it should return 100
calc.rowOne().columnTwo()    # And it should return 200
calc.rowOne().columnThree()  # And it should return 300
calc.rowOne().total()        # And it should return 600

如何正确实施?当然,_total方法的当前实现不起作用,因为我不知道如何在那里传递所需的上下文。这有可能吗?

1 个答案:

答案 0 :(得分:1)

class Calculations
  constructor: (amount = 1000) ->
    @amount = amount

  rowOne: =>
    columnOne:   => @amount * 0.1
    columnTwo:   => @amount * 0.2
    columnThree: => @amount * 0.3
    total:       @_total

  _total: () ->
    this.columnOne() + this.columnTwo() + this.columnThree()