Javascript 在回调函数中访问类属性
我的代码有点小问题。这是:Javascript 在回调函数中访问类属性,javascript,Javascript,我的代码有点小问题。这是: // We are in the constructor of my class this.socket.emit('getmap', {name: name}, function(data){ this.mapData = data.map; this.load(); }); 问题是没有设置mapData属性,事实上,this引用了名称空间套接字如何通过此功能访问此.mapData? 很抱歉我的英语不好…你必须知道JavaScript是如何决定这个
// We are in the constructor of my class
this.socket.emit('getmap', {name: name}, function(data){
this.mapData = data.map;
this.load();
});
问题是没有设置mapData
属性,事实上,this
引用了名称空间套接字如何通过此功能访问此.mapData
?
很抱歉我的英语不好…你必须知道JavaScript是如何决定这个
的值的。在您正在使用的匿名函数中,它通常是全局名称空间或web上的window
对象。在任何情况下,我建议您利用闭包并在构造函数中使用变量
// 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();
});
您需要保存对此
对象的引用。在回调中,此将引用调用函数的对象。一种常见的模式是:
// 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();
});
@palra的可能副本请您将其中一个答案标记为“正确”好吗?@palra我建议您通读javascript中的这个
关键字。例如。谷歌“javascript这个关键字”,你会发现很多解释。