最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing a class property in a callback function - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 16

You need to save a reference to the this object. Inside the callback thiswill 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();
});
发布评论

评论列表(0)

  1. 暂无评论