嵌套函数不能访问全局变量
Nested function can't access global variable
代码:
public loaderShow = false;
Onsubmit(form:any):void{
this.startLoader(this.endLoader);
}
public startLoader(ender) {
this.loaderShow = true;
setTimeout(ender, 2000);
}
public endLoader() {
this.loaderShow = false;
return this.loaderShow;
}
我想要发生的事情:
提交表单时 -> 运行 startLoader -> 将 loaderShow 更改为 true
2 秒后 -> 运行 endLoader -> 再次将 loaderShow 变为 false
发生了什么:
提交表单 -> 运行 startLoader -> 将 loaderShow 更改为 true
2 秒后 -> 运行 endLoader -> 无法访问 loaderShow(认为它未定义)
我需要做的事情:
找到一种方法让 endLoader() 能够找到 loaderShow(但我的尝试失败了。我尝试将它作为参数传递给函数,但我不确定如何对 loaderShow 进行全局更改)。
改变
setTimeout(ender, 2000);
到
setTimeout(ender.bind(this), 2000);
或者,更改
this.startLoader(this.endLoader);
到
this.startLoader(this.endLoader.bind(this));
当你传递函数时,它失去了它的上下文,所以它需要绑定到 class 实例。
代码:
public loaderShow = false;
Onsubmit(form:any):void{
this.startLoader(this.endLoader);
}
public startLoader(ender) {
this.loaderShow = true;
setTimeout(ender, 2000);
}
public endLoader() {
this.loaderShow = false;
return this.loaderShow;
}
我想要发生的事情:
提交表单时 -> 运行 startLoader -> 将 loaderShow 更改为 true
2 秒后 -> 运行 endLoader -> 再次将 loaderShow 变为 false
发生了什么:
提交表单 -> 运行 startLoader -> 将 loaderShow 更改为 true
2 秒后 -> 运行 endLoader -> 无法访问 loaderShow(认为它未定义)
我需要做的事情:
找到一种方法让 endLoader() 能够找到 loaderShow(但我的尝试失败了。我尝试将它作为参数传递给函数,但我不确定如何对 loaderShow 进行全局更改)。
改变
setTimeout(ender, 2000);
到
setTimeout(ender.bind(this), 2000);
或者,更改
this.startLoader(this.endLoader);
到
this.startLoader(this.endLoader.bind(this));
当你传递函数时,它失去了它的上下文,所以它需要绑定到 class 实例。