class Pick{
constructor(id, i){
this.aa=id;
this.kk=i;
}
start(id){
dlog(''+this.aa);
this.run(id);
}
run(id){
if(this.kk > 10) return;
dlog('标记1:'+this.aa+" "+this.kk+id);//标记1
thread(function (){
dlog('标记2:'+this.aa+" "+this.kk+id);//标记2
this.kk++;
this.run(id);
}, 1000*5);
}
}
function dlog(msg){
console.log(msg);
}
function thread(callBack, time){
setTimeout(function(){
callBack();
}, time);
}
使用
let picker_id = 'test'
let pick = new Pick(picker_id, 0);
pick.start(picker_id);
报错
Uncaught TypeError: Cannot read property 'aa' of undefined
报错的是“标记2”这行代码。一样的代码,”标记1“倒没有报错。线程里面就报错,请问应该如何修改呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
匿名函数this指向丢失问题导致的吧。你在run中调用thread传入的函数是匿名函数this指向有问题,后面加个bind(this)或者用箭头函数吧
thread 异步执行 this 指上的不是 类
所以报错,传递变量