鍍金池/ 問答/HTML/ es6的class中函數(shù)之間調(diào)用報錯?

es6的class中函數(shù)之間調(diào)用報錯?

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
請問應該怎么改?

回答
編輯回答
脾氣硬

this指向的問題

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

解決方案:使用箭頭函數(shù)

img.onload= () => {
    this.render(imgInfo,num);
    num++;
}
2018年7月21日 03:04
編輯回答
枕邊人
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.
2017年12月25日 19:22