gpt4 book ai didi

javascript - 我可以在下面的示例中增加 'this' 的范围吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:55:35 24 4
gpt4 key购买 nike

在使用 jquery 回调时,我发现“this”不再被定义。我找到了解决方法,即将“this”设置为另一个变量。例如,像这样:

function handler(DATA) {
var myThis = this;

$.post(
'file.php',
DATA,
function() {

// THIS where I need access to 'this', but its not available
// unless I've used the 'myThis' trick above

}
);
}

它是这样工作的,但我一直在寻找“正确的方法”或“更好的方法”来做事。

这是最好的方法吗?或者还有另一个?

最佳答案

这很好。我在我的项目中一直这样做,尤其是在使用 Ajax 调用时。

但是,请确保将 var 放在 myThis 之前,否则它将在全局范围内声明,这是您绝对不希望看到的。

function handler(DATA) {
var myThis = this;

$.post(
'file.php',
DATA,
function() {

// THIS where I need access to 'this', but its not available
// unless I've used the 'myThis' trick above

}
);
}

关于javascript - 我可以在下面的示例中增加 'this' 的范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766559/

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