打字稿中的递归未定义 [英] recursion in typescript gets undefined

查看:42
本文介绍了打字稿中的递归未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在组件内使用画布对象来生成图表.为了让它动画,我递归地调用该方法.我不断收到错误消息,说该方法未定义.不确定我需要如何构建它.

I'm using a canvas object inside my component to generate a chart. In order for it animate i'm calling the method recursively. I keep getting an error saying that the method is not defined. Not sure how I need to structure it.

感谢任何帮助.

 // Animate function
protected animate(draw_to) {
// Clear off the canvas
this.ctx.clearRect(0, 0, this.width, this.height);
// Start over
  this.ctx.beginPath();
// arc(x, y, radius, startAngle, endAngle, anticlockwise)
// Re-draw from the very beginning each time so there isn't tiny line spaces between each section (the browser paint rendering will probably be smoother too)
  this.ctx.arc(this.x, this.y, this.radius, this.start, draw_to, false);
// Draw
  this.ctx.stroke();
// Increment percent
  this.curr++;
// Animate until end
  if (this.curr < this.finish + 1) {
    // Recursive repeat this function until the end is reached
    requestAnimationFrame(function () {
      error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
    });
  }
}

推荐答案

您需要使用箭头函数来在您提供给 requestAnimationFrame 的函数中保持相同的上下文.

You need to use an arrow function to keep the same context in the function you give to requestAnimationFrame.

requestAnimationFrame(() => {
      error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
    });

这篇关于打字稿中的递归未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆