var self =这在Coffeescript中

时间:2013-09-04 19:04:28

标签: javascript coffeescript

我正在处理使用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) )

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

提前致谢,

2 个答案:

答案 0 :(得分:18)

Use the fat arrow.

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

编译为:

var _this = this;

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

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

答案 1 :(得分:1)

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

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

    ....

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

相关问题