9

我在使用 Coffeescript 时正在处理一些范围问题。

drawFirstLine: (currentAngle)  ->
    currentAngle = currentAngle # = 1

    switch @type
        # set @endAngle to pick up later on
        # Math.PI * 2 is the endpoint of a circle divided by seconds times current seconds
        when "seconds" then @endAngle = Math.PI * 2 / 60 * @seconds
        when "minutes" then @endAngle = Math.PI * 2 / 60 * @minutes
        when "hours" then @endAngle = Math.PI * 2 / 24 * @hours


    @context.arc(@center_x, @center_y, 100, @startAngle, currentAngle, @counterClockWise)
    @context.lineWidth = 15

    console.log('drawn')

    text = "28px sans-serif";
    @context.fillText(text, @center_x - 28, @center_y - @canvas.width / 5)

    @context.stroke()


    currentAngle++;
    if currentAngle < @endAngle
        requestAnimationFrame( -> @drawFirstLine(currentAngle / 100) )

正如您在上面代码的底部看到的那样,我试图一次又一次地调用我们所在的函数。但问题是我不能@drawFirstLine在另一个函数(requestAnimationFrame 函数)中使用。在普通的 javascript 中,我可以使用var self = this和引用 self. 但是有谁知道如何在咖啡脚本中处理这个问题?

提前致谢,

4

2 回答 2

18

使用粗箭头。

requestAnimationFrame( => @drawFirstLine(currentAngle / 100) )

编译为:

var _this = this;

requestAnimationFrame(function() {
  return _this.drawFirstLine(currentAngle / 100);
});

它基本上是self = this为你做的,使this@在函数内部声明该函数时是什么this。它非常方便,它可能是我最喜欢的 coffeescript 功能。

于 2013-09-04T19:10:05.390 回答
1

我一直在我的工作应用程序中这样做。

drawFirstLine: (currentAngle)  ->
    currentAngle = currentAngle # = 1
    self = @

    ....

请记住,在 Coffeescript 中你不需要var: 这将保持在drawFirstLine函数上下文的本地。(它会生成var self = this)。

于 2013-09-05T02:13:21.490 回答