【问题标题】:call function in canvas在画布中调用函数
【发布时间】:2022-01-26 02:33:27
【问题描述】:

尝试在画布中调用函数时出现错误core.js:6241 ERROR TypeError: this.test is not a function at klass.<anonymous>

HTML

<canvas #canvas id="canvas" width="900" height="400"></canvas>

ts

ngOnInit() {

this.cvs.on("stagemouse:down", function(){
      console.log('Event mouse:down Triggered');
      this.test();
    })
  }

test(){
  console.log("test");
}

【问题讨论】:

  • 尝试使用箭头函数定义,可能this指的是画布而不是你的组件在这个上下文中

标签: angular typescript canvas


【解决方案1】:

使用function() 定义函数时,它不是“绑定”的,这意味着this 的值可能并不总是相同,具体取决于调用函数的时间和地点。要声明“绑定”函数,请使用箭头语法:

this.cvs.on("stagemouse:down", () => {
  console.log('Event mouse:down Triggered');
  this.test();
});

这种语法使得函数中的this总是引用创建时当前存在的this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2019-11-29
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2013-09-01
    相关资源
    最近更新 更多