gpt4 book ai didi

javascript如何在回调函数中获取this.variable

转载 作者:搜寻专家 更新时间:2023-11-01 04:47:27 25 4
gpt4 key购买 nike

在下面javascript自定义类中,在回调中,为什么this.obj没有任何东西,只有局部变量obj有我想要的东西?谢谢。

function ClassTest(director) {
this.obj = {"test1": "test1"};
}

function test1(input, callback) {
callback("success");
}

ClassTest.prototype.test = function() {
var obj = this.obj;
test1("niuniu",function(e){
console.log(this.obj); // undefined
console.log(obj); // this one has stuff
});
}

// run
new ClassTest().test()

最佳答案

因为 test1 中的函数正在创建一个具有不同 this 上下文的新作用域。典型的解决方案是 bind 或缓存 this:

绑定(bind):

test1("niuniu",function(e){
console.log(this.obj);
}.bind(this));

缓存:

var self = this;
test1("niuniu",function(e){
console.log(self.obj);
});

关于javascript如何在回调函数中获取this.variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670359/

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