【问题标题】:How to access variables inside a function from outside in another function in typescript?如何在打字稿的另一个函数中从外部访问函数内部的变量?
【发布时间】:2018-08-10 18:02:24
【问题描述】:
在我的 html 页面 onchange 中,我只是通过传递参数来调用一个方法。检索值后,单击另一个按钮 Im 调用函数 2。我需要在同一个类中使用 function2 中的函数变量。我使用 Angular 6 和打字稿。我的 ts 文件如下所示。
export class component extends Lifecycle {
cc1: string;
constructor (){}
Function (cc1,cc2)
{
this.cc1 = cc1;
// return cc1;
}
Function2 (){
console.log(cc1);
}
}
有人可以帮我解决这个问题吗?
【问题讨论】:
标签:
angular
function
typescript
angular6
【解决方案1】:
在任何方法中使用this关键字来访问与类相关的任何属性或方法。
export class component extends Lifecycle {
cc1: string;
constructor() {
super();
}
Function(cc1, cc2) {
this.cc1 = cc1;
// return cc1;
}
Function2() {
console.log(this.cc1);
}
}
如果你扩展类,你必须调用super
【解决方案2】:
在Function2 中,您将使用this.cc1 如下所示(请注意,我将传递给Function1 的参数重命名以阐明它们与类级变量的区别)
export class component extends Lifecycle {
cc1: string;
constructor () {
super();
}
Function1 (_cc1, _cc2) {
this.cc1 = _cc1;
}
Function2 () {
console.log(this.cc1);
}
}
【解决方案3】:
在函数 2 中
Function2 (){
console.log(this.cc1);
}
}