Cc.class 属性访问问题

cc.Class({
extends: cc.Component,
properties: {
urlState:1,
},
onLoad: function () {
notice.addObserver(this,this.onMessage,comMsg.SOCKET_MESSAGE);
notice.addObserver(this,this.onSocketConnected,comMsg.SOCKET_CONNECTED);
var self=this;
single.startSocket(“ws://121.40.153.130:2019”, self);
});
},
onMessage: function(data){
if(data.type==comMsg.LOGIN_MSG_TYPE){
if(data.success==1){
if(gameSys.reLoginURL!=""){
single.startSocket(gameSys.reLoginURL, this);
this.urlState=2;
return;
}
}
}
},
onSocketConnected:function(data){
var curState=this.urlState;
//首次登陆跳转
if(curState==2){
var paras={type:comMsg.REDIRCT_MSG_TYPE};
socketPack.sendData(paras);
//var sMsg=socketPack.bindSendData(paras);
//single.sendPacket(JSON.stringify(sMsg));
}
},
});

想问下为什么urlState在onMessage中能获取到值,但在onSocketConnected无法获取到值是何原因,

应该是你把this.onMessage和this.onSocketConnected当作闭包传递给了notice.addObserver,它们执行时的this就不是指向你这个class了。onMessage里面你赋值urlState其实不是你这个class的urlState。给notice.addObserver作参数时应当写成:this.onMessage.bind(this)和this.onSocketConnected.bind(this)。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind