eATM

ES6中 class成员函数单独使用或回调时找不到this的问题

class Logger{
    constructor()
    {
        this.x=1;

        //利用bind使getX单独使用时也能使用this指针
        //this.getX=this.getX.bind(this);
    }

    getX()
    {
        //如果单独调用getX函数,this将为undefined
        return this.x;
    }

    //另外一种解决方式
    //使用箭头定义函数时,this将指向函数外层对象
    getY=()=>{
        return this.x;
    }
}

let log=new Logger();
let getX=log.getX;
getX();  //单独调用 或者 回调此函数时


//解决方法,在Logger构造函数中重构getX,为其绑定this
this.getX=this.getX.bind(this);

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注