I got a little problem in my code. Here it is :
// We are in the constructor of my class
this.socket.emit('getmap', {name: name}, function(data){
this.mapData = data.map;
this.load();
});
The problem is that the mapData
attribute isn't set, in fact, this
refers to the namespace Socket. How can I access to this.mapData
through this function ?
And sorry for my bad english ...
I got a little problem in my code. Here it is :
// We are in the constructor of my class
this.socket.emit('getmap', {name: name}, function(data){
this.mapData = data.map;
this.load();
});
The problem is that the mapData
attribute isn't set, in fact, this
refers to the namespace Socket. How can I access to this.mapData
through this function ?
And sorry for my bad english ...
Share Improve this question edited May 14, 2013 at 21:48 DarkChipolata asked May 14, 2013 at 21:43 DarkChipolataDarkChipolata 9651 gold badge12 silver badges29 bronze badges 2- possible duplicate of Event Handler Called With Wrong Context – Felix Kling Commented May 14, 2013 at 21:51
- @palra would you mark one of the answers as "correct" please? – Aaron Gibralter Commented May 15, 2013 at 17:41
2 Answers
Reset to default 16You need to save a reference to the this
object. Inside the callback this
will refer to the object on which the function has been called. A mon pattern is this:
// We are in the constructor of my class
var self = this;
this.socket.emit('getmap', {name: name}, function(data){
self.mapData = data.map;
self.load();
});
You have to be aware of how JavaScript determines the value of this
. In anonymous functions like the one you're using, it's usually the global namespace or window
object on the web. In any case, I would just suggest you take advantage of the closure and use a variable in your constructor.
// We are in the constructor of my class
var _this = this;
this.socket.emit('getmap', {name: name}, function(data){
_this.mapData = data.map;
_this.load();
});