var that = this 小坑记

在js编码过程中,经常会使用如上的语句来规避拿不到变量的问题。

比如:

queryData:function () {
            var that=this;
            var param={};
            for(var key in this.condition){
                if(this.condition[key]){
                    param[key]=this.condition[key];
                }
            }
            AJAX.GET("/api/adream/flow/queryRoomsBySystem",param,function (data){
                if(data.success && data.systemList != null){
                    var queryLen = data.systemList.length;
                    if(queryLen > 0){
                        for (var queryIndex=0; queryIndex<queryLen; queryIndex++){
                            debugger;
                            that.roomList.push(data.systemList[queryIndex]);
                        }
                    }
                }
            });

注意标黄的部分,如果用this.roomList,将会发现roomList为空对象,是因为this指向的是AJAX内部的对象,this会随着代码进入的层深来自动改变指向的对象,所以这里在用this.roomList,那确实拿不到外层的对象。

而使用var that = this之后,that中的对象将是this刚进入queryData方法时候的副本,所以会拿到这个对象。

猜你喜欢

转载自www.cnblogs.com/scy251147/p/10289132.html