【问题标题】:var self = this in Coffeescriptvar self = Coffeescript 中的 this
【发布时间】:2013-09-05 10:13:21
【问题描述】:

我在使用 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 并引用 self.但是有人知道如何在咖啡脚本中处理这个问题吗?

提前致谢,

【问题讨论】:

标签: javascript coffeescript


【解决方案1】:

Use the fat arrow.

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

编译为:

var _this = this;

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

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

【讨论】:

  • 但是如果你有几个回调深度,你在使用胖箭头时会不会仍然遇到麻烦?还是总是指最外层的 this?
  • @RyanWilcox 如果您在嵌套函数时继续使用=&gt;,则将保留thisThe proof is here!
【解决方案2】:

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

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

    ....

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-18
    • 2011-05-21
    • 2012-07-19
    • 1970-01-01
    • 2015-06-01
    • 2021-06-09
    • 2010-09-25
    相关资源
    最近更新 更多