如何从打字稿中另一个函数的外部访问函数内部的变量?

时间:2018-08-10 18:02:24

标签: angular function typescript angular6

在我的html页面onchange中,我只是通过传递参数来调用方法。检索值后,单击另一个按钮Im会调用function2。我需要在同一类的function2中使用来自function的变量。我正在使用角度6和打字稿。我的ts文件如下。

 export class component extends Lifecycle {
  cc1: string;
  constructor (){}
  Function (cc1,cc2)
  {
   this.cc1 = cc1;
   // return cc1;
   }

  Function2 (){
      console.log(cc1);
    }
  }

有人可以帮我吗?

3 个答案:

答案 0 :(得分:2)

在任何方法中使用this关键字来访问与类相关的任何属性或方法。

export class component extends Lifecycle {
    cc1: string;
    constructor() {
        super();
    }
    Function(cc1, cc2) {
        this.cc1 = cc1;
        // return cc1;
    }

    Function2() {
        console.log(this.cc1);
    }
}
  

如果扩展课程,您必须致电super

答案 1 :(得分:1)

Function2中,您将使用this.cc1,如下所示(请注意,我重命名了传递给Function1的参数以阐明它们与类级变量的区别)

export class component extends Lifecycle {
  cc1: string;

  constructor () {
    super();
  }

  Function1 (_cc1, _cc2) {
    this.cc1 = _cc1;
  }

  Function2 () {
    console.log(this.cc1);
  }
}

答案 2 :(得分:0)

在功能2中

Function2 (){
      console.log(this.cc1);
    }
  }
相关问题