在网络接口回调中,如何调用界面的this,如例子?

HttpService.test(account, pwd, this.test);

private test(params : any)
{
this.node.destroy(); //报错,找不到this
}

static HttpService.test(callback ?: ((params : any) => void))
{
let url = “http…”;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 207) {
let response = xhr.responseText;
let data = JSON.parse(response);
callback(data);
} else {
callback(null);
}
} else {
console.log(“onCreateAccountStateChange xhr.readyState is:”, xhr.readyState, "xhr.status is: ", xhr.status)
}
};
xhr.open(“POST”, url, true);
xhr.send();

}

当然先试用静态变量保存this是可以的,但是有办法可以直接调用this吗?我使用的TS

相关,js 闭包

1赞

HttpService.test(account, pwd, this.test.bind(this));

1赞

蟹蟹回复,受教了

回调函数的执行有3种方式:

  1. callback(param1, param2)
  2. callback.call(target, param1, param2)
  3. callback.apply(target, [param1, param2])

你这里的问题, 可以用 bind来解决, 但理解上面的3种回调方式, 你就不会问这个问题.
javascript this 的指向问题, 还是有很多新人不了解, 希望新人都看下:
http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html

1赞