Ish*_*ngi 1 javascript class typescript angular
我有一个管理特定对话框的单独对象。考虑以下代码。由于很容易想象函数的作用,因此我无法访问该类的实例。我尝试使用传统that = this方法。
export class Whatever implements OnInit {
that = this;
dialog = {
data:{},
open:function() {
//way to access 'that' variable
},
close:function() {},
toggle:function() {}
}
//other declarations and functions
}
Run Code Online (Sandbox Code Playgroud)
当我的应用程序扩展时,此服务中有太多功能。因此,我试图将这些功能中的一些整合到对象中,这将使代码更清晰。
另外,如果有更好的方法,我也想知道。谢谢。
最好的方法是function(){}用ES6箭头函数代替,该函数可以this像这样保持您的上下文() => {}。
您也可以使用functions(){}.bind(this),但是最好只使用箭头功能。两者都会使您this在函数主体中按预期引用