javascript – var self = 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并引用自己.但是有人知道如何在咖啡书中处理这个问题吗?

提前致谢,

解决方法

Use the fat arrow.
requestAnimationFrame( => @drawFirstLine(currentAngle / 100) )

其编译为:

var _this = this;

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

它基本上是为你自己,这使得这个或@在函数内部,当这个函数被声明时是什么.这很方便,这可能是我最喜欢的咖啡书.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...