"This" paper.js 事件中的关键字进入构造函数

"This" keyword in paper.js event into constractor

我尝试在 paper.js 和 typescript 之间进行交互。

所以我想将一些事件处理程序写入 PenTool 的构造函数中。 (因为我想在创建工具时使用 DI 并定义所有纸张事件)

我有下一段代码:

export class PenTool implements BaseTool {

name: string;
toolType: Tools;
tool: any;
drawingContext: any;
path: any;

constructor(private paperService: PaperService) {

    this.name = "Pen";
    this.toolType = Tools.Pen;
    this.drawingContext = this.paperService.getDrawingContext();

    this.tool = new this.drawingContext.Tool();

    this.tool.onMouseDown = function (event) {

        //!!!!!!!!!!!!!!!!!!!
        //I want to use my class property here (this.name) or
        //(this.drawingContext) etc, but I can't!

        this.path = new (paperService.getDrawingContext()).Path();
        //this.path = new this.drawingContext.Path();
        this.path.add(event.point, event.point);
        this.path.strokeColor = 'black';
    }

    this.tool.onMouseDrag = function (event) {

        console.log('pen -> mouse drag!');

        if (event.modifiers.shift) {
            this.path.lastSegment.point = event.point;
        } else {
            this.path.add(event.point);
        }
    }
}

}

paperService 给我 paper 变量,创建新的 paperScope 等。 问题是我无法访问事件函数中的 class 属性。

我做错了什么? 提前致谢。

改用箭头函数来保持相同的上下文。

export class PenTool implements BaseTool {

  name: string;
  toolType: Tools;
  tool: any;
  drawingContext: any;
  path: any;

  constructor(private paperService: PaperService) {

    this.name = "Pen";
    this.toolType = Tools.Pen;
    this.drawingContext = this.paperService.getDrawingContext();

    this.tool = new this.drawingContext.Tool();

    this.tool.onMouseDown = (event) => {

      //!!!!!!!!!!!!!!!!!!!
      //I want to use my class property here (this.name) or
      //(this.drawingContext) etc, but I can't!

      this.path = new(paperService.getDrawingContext()).Path();
      //this.path = new this.drawingContext.Path();
      this.path.add(event.point, event.point);
      this.path.strokeColor = 'black';
    }

    this.tool.onMouseDrag = (event) => {

      console.log('pen -> mouse drag!');

      if (event.modifiers.shift) {
        this.path.lastSegment.point = event.point;
      } else {
        this.path.add(event.point);
      }
    }
  }

}

This post 有很多关于 this 如何在 javascript.

中工作的信息