Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在回调函数中访问类属性_Javascript - Fatal编程技术网

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这个关键字”,你会发现很多解释。