我有一个单独的对象来管理特定的对话框。考虑以下代码。由于很容易想象函数的作用,但是我无法访问该类的实例。我尝试使用传统的 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
}
随着我的应用程序的扩展,我在这个服务中有太多的功能。所以我试图将其中一些函数合并到对象中,这将使代码更清晰。
此外,如果有任何更好的方法,我很想知道。谢谢。
最佳答案
最好的方法是将 function(){}
替换为 ES6 箭头函数,它像这样保存您的 this
上下文 () => { }
。
您也可以使用 functions(){}.bind(this)
,但最好只使用箭头函数。两者都会按照预期在函数体中保留对 this
的引用
关于javascript - 在实例对象内的函数中获取类(this)的实例 - typescript /Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478318/