为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2019-02-21 18:15:25
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请问应该怎么改?
查看完整描述

1 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

this指向的问题


img.onload=function(){

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

    num++;

}

解决方案:使用箭头函数


img.onload= () => {

    this.render(imgInfo,num);

    num++;

}


查看完整回答
反对 回复 2019-02-26
  • 1 回答
  • 0 关注
  • 585 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号