gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:03:10 24 4
gpt4 key购买 nike

这是我拥有的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()

关于javascript - 在 Coffeescript 中调用方法并传递适当的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34511921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com