es6的class中函数之间调用报错?

class Barrel{
    constructor(ele){
        this.ct=ele;
        this.baseHeight=100;
        this.maxWidth=ele.style.width;
        this.lastRowWidth=0;
        this.imgList=[];
        this.data=[];
    }
    createImg(arr){
        let num=0;
        for(let i in arr){
            this.data.push(arr[i]);
        }
        for(let i in this.data){
            let img=new Image();
            img.src=this.data[i];
            img.onload=function(){
                let imgHeight=img.height;
                let imgWidth=img.width;
                let proportion=imgWidth/imgHeight;
                let imgInfo={
                    self:img,
                    width:this.baseHeight*proportion,
                    height:this.baseHeight
                }
            
                this.render(imgInfo,num);
                num++;
            }
        }
    }
    render(imgInfo,num){...}

报错信息:Uncaught TypeError: this.render is not a function
请问应该怎么改?

阅读 3.7k
2 个回答

this指向的问题

img.onload=function(){
    this.render(imgInfo,num); // this指向img,而不是Barrel。img没有render方法,所以报错
    num++;
}

解决方案:使用箭头函数

img.onload= () => {
    this.render(imgInfo,num);
    num++;
}
img.onload=()=>{
                let imgHeight=img.height;
                let imgWidth=img.width;
                let proportion=imgWidth/imgHeight;
                let imgInfo={
                    self:img,
                    width:this.baseHeight*proportion,
                    height:this.baseHeight
                }
            
                this.render(imgInfo,num);
                num++;
            }
 你的this没有指向当前class.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题