The easiest solution is to use that
var that = this; //that is a normal variable //so it is lexically scoped //and can be used in inner functions socket.on('connect', function(data){ var p = that.NickName; });
Another possibility explicitly binds this value to the callback function
socket.on('connect', function(data){ var p = this.Nickname; }.bind(this));
that three has the advantage of nesting as many callbacks as possible, and the binding version has the advantage that you can use "this" inside.
The disadvantage of the binding method is that it is not supported in IE <= 8, so you may need to use padding if you need to support older browsers.
edit: This answer is a bit outdated. Currently, you probably no longer need to worry about IE6, and you can use the thick arrow syntax that does not overwrite this .
source share