typescript 如何从打字稿中的嵌套函数中调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41656047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call a function from within a nested function in typescript?
提问by user3107338
I want to call the function func2
from within sample function of function func1
. Can someone suggest a way to achieve that?.
我想func2
从 function 的示例函数中调用该函数func1
。有人可以建议一种方法来实现这一目标吗?
class A
{
public func1()
{
let sample = function()
{
//call func2... but how?
}
}
public func2()
{
}
}
Thanks in Advance
提前致谢
回答by Tha'er M. Al-Ajlouni
Use the this
keyword with the arrow
function notation like this:
使用this
带有arrow
函数符号的关键字,如下所示:
class A
{
public func1()
{
let sample = () =>
{
this.func2();
}
}
public func2()
{
}
}
The trick is using the arrow
function, because the arrow
function changes the definition of this
to be the instance of the class
instead of the current scope.You can read more here
诀窍是使用该arrow
函数,因为该arrow
函数将 的定义更改this
为 的实例class
而不是当前范围。您可以在此处阅读更多信息