在Coffeescription中调用方法并传递正确的上下文

Calling methods and passing proper context in Coffeescript

本文关键字:上下文 Coffeescription 调用 方法      更新时间:2023-09-26

这是我拥有的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方法的当前实现不起作用,因为我不知道如何在那里传递所需的上下文。这可能吗?

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()