这是我的客户端JS脚本
var Chat = function(username) {
that = this;
this.myUser = {"username":username};
this.socket = io(server);
this.socket.on('connect', function(){
console.log(that.myUser); // this is UGLY but this.myUser will give an error
});
}
任何想法如何摆脱那个令人讨厌的“那=这个”?
答案 0 :(得分:3)
您可以使用bind()
:
var Chat = function(username) {
this.myUser = {"username":username};
this.socket = io(server);
this.socket.on('connect', function(){
console.log(this.myUser);
}.bind( this ) );
};
但说实话,我个人并不认为,这要好得多。