调用ajax后,如何在javascript方法中保留上下文?
嗨,我对es6有一个问题,尤其是课堂教学方法。参见我的示例: 我的第一节课:调用ajax后,如何在javascript方法中保留上下文?,javascript,ecmascript-6,Javascript,Ecmascript 6,嗨,我对es6有一个问题,尤其是课堂教学方法。参见我的示例: 我的第一节课: class A{ constructor(){ this.B = new B(); this.test = 5; } methodA1(){ B.methodB1(this.methodA2); } methodA2(){ console.log(this.test); } } 第二类: class
class A{
constructor(){
this.B = new B();
this.test = 5;
}
methodA1(){
B.methodB1(this.methodA2);
}
methodA2(){
console.log(this.test);
}
}
第二类:
class B{
methodB1(callback){
$.get("url",function(data){
...
callback();
});
}
}
当您执行methodA1时,代码返回:这是未定义的(在MethodA2中)!
事实上,在ajax调用中调用回调函数时,回调会丢失类的上下文。有人有办法回避这个问题吗
谢谢。您可以使用绑定此
methodA1(){
this.B.methodB1(this.methodA2.bind(this));
}
由于未正确引用在构造函数中创建的
B
属性,因此会出现错误
如果确定将在类A的上下文中调用methodA1,则可以通过this.B
引用属性B
。this
conext将指向存在B
的A类参考:
class A{
constructor(){
this.B = new B();
this.test = 5;
this.methodA2 = this.methodA2.bind(this);
// I prefer to bind my methods in the constructor so they are bound once
}
methodA1(){
this.B.methodB1(this.methodA2);
// ^ -- the B property created in constructor B exists as a property
// of this class, to reference it within a class method you need
// to call this.B
}
methodA2(){
console.log(this.test);
}
}
class B{
methodB1(callback){
$.get("url",function(data){
...
callback();
});
}
}
const a = new A();
a.methodA1(); // will log out 5 when the `$.get` request has its callback invoked
这就是异步操作的本质。调查承诺。()回答正确,但不修复原始代码中的错误:
this.B.methodB1(this.methodA2.bind(this))代码>我已编辑,谢谢!