当回调ES 2016类定义时,我如何将"this=self"用于类


class ForwardHistLumb{
var self = this;  //I can't declare members here.
constructor(){ 
this.self = this;
$.ajax({
url: getForwardHistLumbUrl,
type: 'POST',
dataType: 'json',
data: [],
success: function(data) {
this.testFunc(); // undefined error
this.self.testFunc() // same error 
self.thisFunc(); // of course error
}
});
testFunc(){
console.log("hello") 
}
}

在ES2016之前,我可以将成员变量声明为var self = this

所以我可以在回调函数中使用self。

然而,类中的变量声明现在是不可能的。

我该如何解决??


根据@Kartik Anand的说法,我使用"绑定"更改了代码,但出现了相同的错误????

class ForwardHistLumb{
var self = this;  //I can't declare members here.
constructor(){ 
this.testFunc() = this.testFunc.bind(this)
$.ajax({
url: getForwardHistLumbUrl,
type: 'POST',
dataType: 'json',
data: [],
success: function(data) {
this.testFunc()/////??????
}
});
testFunc(){
console.log("hello") 
}
}

您可以在成功回调中使用箭头函数

class ForwardHistLumb {
constructor() {
$.ajax({
url: 'https://httpbin.org/get',
type: 'GET',
dataType: 'json',
data: [],
success: data => {
this.testFunc(data)
}
})
}
testFunc(data) {
console.log(data)
}
}

或者,如果您想保留AJAX对象的上下文,可以在构造函数中保存对该类方法的引用。

class ForwardHistLumb{
constructor() { 
const testFunc = this.testFunc
$.ajax({ 
url: 'https://httpbin.org/get',
type: 'GET',
dataType: 'json',
data: [],
success: function() {
testFunc(this)  
}
})
}

testFunc(data) {
console.log(data)  
}
}

您应该使用Function.prototype.bind来保留this的值,或者简单地使用箭头函数,因为它不会根据上下文更改this

使用与您相同的原则,这应该是有效的:

class Testing {
constructor() {
var self = this;
// this represents your ajax callback
setTimeout(function() {
self.result()
}, 1000);
}
result() {
console.log('hello');
}
}
new Testing();

但是,请考虑使用"胖箭头"(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)维护this的上下文

class Testing {
constructor() {
// cleaner approach keeping your constructor less poluted
this.asyncFn();
}
asyncFn() {
// this represents your ajax callback
setTimeout(() => {
this.result()
}, 1000);
}
result() {
console.log('hello');
}
}
new Testing()
class ForwardHistLumb {
constructor() {
const self = this;
$.ajax({
url: getForwardHistLumbUrl,
type: 'POST',
dataType: 'json',
data: [],
success: function(data) {
self.testFunc();
}
});
}
testFunc() {
console.log('hello');
}
}

相关内容

最新更新