首页 > 解决方案 > TypeScript:如何调用父类中的函数?

问题描述

在 nodes.tsx 我正在导入 InputHandler

import { InputHandler } from './inputHandler';

class Nodes {
  canvasWidth: number;
  canvasHeight: number;

  constructor(width: number, height: number) {
    this.canvasWidth = width;
    this.canvasHeight = height;
    new InputHandler(this);
//         ^ error
  }
  clicked() {
    console.log('clicked');
  }
}

export { Nodes };

我得到错误unused expression, expected an assignment or function call (no-unused-expression)tslint(1)

class InputHandler {
    constructor(nodes: any) {
//                      ^ error, im passing in `this` from the parent
        document.addEventListener('click', (event) => {
            nodes.clicked();
        });
    }
}

export { InputHandler };

在输入处理程序内部,我正在尝试调用clicked()父级。我也收到错误 Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type. (no-any)tslint(1)

当我单击画布或页面时,不会调用 clicked() 函数。

我觉得整个模式是错误的?

标签: typescript

解决方案


这不是你使用构造函数的方式:

const handler = new InputHandler(this);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor


推荐阅读