繁体   English   中英

如何使用在构造函数中创建的 function?

[英]How to use a function that was created inside the constructor?

我正在构造函数中创建一个 function ,它需要在构造函数中完成,我想要一个按钮来从外部激活它,但是我不知道该怎么做。

我的 TypeScript

  private functionActive;

  constructor(){

    this.functionActive = function hello(){

      console.log('Hello world');

    };

    }   

  }

  buttonActive(event){

    this.functionActive.hello();

  }

两个错误:

  1. 定义 function 没有额外的)

     constructor() { this.functionActive = function hello() { console.log("Hello world"); }; }
  2. 使用 function 的引用调用它,即functionActive而不是hello ,因为它是 function 表达式:

     buttonActive(event) { this.functionActive(); }

如果我的问题是正确的,这是解决问题的方法:

private functionActive={};

  constructor(){

    this.functionActive["hello"] = function (){
      console.log('Hello world');
    }
    }   

  buttonActive(event){
    this.functionActive.hello();

  } 

这是工作演示: demo

class A {
  private functionActive;
  constructor(option) {
    if (option.enable)
      this.functionActive = function () {
        console.log("Hello world");
      };
  }
  buttonActive(event) {
    if (typeof this.functionActive === "function") this.functionActive();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM