在 canvas 中调用函数

call function in canvas

尝试调用 canvas

中的函数时出现错误 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");
}

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

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

此语法使函数 中的 this 始终 引用创建时当前存在的 this