I wonder if someone can help me. Coming from a Java, C++ background I am trying to write a neat OO implementation in Javascript. I am using the following pattern with Socket.io.
In the listen function, the instance variables are properly defined on the first alert. The x instance variable goes out of scope in the socket.on event listener and both instance variables go out of scope in the JQuery $.each
Can someone explain what is going on here ?
var Player = (function () {
this.x = "";
//Constructor
var Player = function() {
// connect to the server
this.x = "somevalue";
this.socket = io.connect();
};
Player.prototype = {
constructor: Player,
listen: function() {
alert(this.x + " " + this.socket); // fine get somevalue & [object, object]
this.socket.on('event', function(data) {
alert(this.x + " " + this.socket); // this.x undefined this.socket [object, object]
$.each(data, function(index,value) {
alert(this.x + " " + this.socket); // undefined undefined
});
});
}
return Player;
})();
this
to refer to in the outer anonymous function context? It will bewindow
(the global object) orundefined
if you're in "strict" mode. – Pointy Sep 25 '13 at 21:56this
behaves. I've found this to be a great spin-up to how Javascript is different: bonsaiden.github.io/JavaScript-Garden – Scott Mermelstein Sep 25 '13 at 21:57this
is very different from Java'sthis
. Also,x
is not a "variable" but a property of your object. – Bergi Sep 25 '13 at 22:55