javascript - js 一个面向对象报错的问题
本文介绍了javascript - js 一个面向对象报错的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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倒没有报错。线程里面就报错,请问应该如何修改呢?
解决方案
匿名函数this指向丢失问题导致的吧。你在run中调用thread传入的函数是匿名函数this指向有问题,后面加个bind(this)或者用箭头函数吧
这篇关于javascript - js 一个面向对象报错的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文