gpt4 book ai didi

javascript - 如何在内部类中找到正确的 "this"对象?

转载 作者:行者123 更新时间:2023-11-30 10:12:35 24 4
gpt4 key购买 nike

<分区>

我正在写一段这样的 JavaScript:

MyClassA.prototype.method1 = function(){
//here, "this" refers to my instance of MyClassA
$.ajax({
url : "http://foo.com/foo",
success: function(data) {
//OMG! "this" now refers to another object
}
}
});

我需要在 success 函数中访问 MyClassAthis 元素。在 Java 中,可以使用 MyClassA.this 来引用内部类中正确的 this 实例。在 JavaScript 中是否有类似的方法来做到这一点?

MyClassA.prototype.method1 = function(){
var myClassAThis=this;
$.ajax({
url : "http://foo.com/foo",
success: function(data) {
myClassAThis.method2();
...
}
}
});

在这种情况下的标准处理方式是什么?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com