Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.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_Class_Oop_Anonymous Function - Fatal编程技术网

Javascript 从异步调用访问成员方法

Javascript 从异步调用访问成员方法,javascript,class,oop,anonymous-function,Javascript,Class,Oop,Anonymous Function,我试图从代码异步调用的方法访问我的“类”中的方法 这是我的简化课程: function FileProcessor(file, callback) { this.file = file; this.callback = callback; } FileProcessor.prototype.readerOnload = function(e) { this.callback(e.target.result); }; FileProcessor.prototyp

我试图从代码异步调用的方法访问我的“类”中的方法

这是我的简化课程:

function FileProcessor(file, callback) {    
    this.file = file;
    this.callback = callback;
}

FileProcessor.prototype.readerOnload = function(e) {
    this.callback(e.target.result);
};

FileProcessor.prototype.process = function() {
    var reader = new FileReader();
    reader.onload = this.readerOnload;

    if (this.file.type == 'text/xml') {
        reader.readAsText(this.file);
    }
};
我对this.callback的cal从构造函数FileProcess开始工作,从process()开始工作,但从ReaderLoad开始不工作。我得到:

未捕获类型错误:未定义不是函数

知道我做错了什么吗


谢谢

我想您的
readerOnLoad
函数是在不同的上下文中调用的,您最终得到的
这个
值不是
文件处理器
的实例

试试这个:

reader.onload = this.readerOnload.bind(this);
或者,如果您必须支持较旧的浏览器:

var self = this;
reader.onload = function(e) { self.readerOnLoad(e); };

您可能想完全省略
readerLoad
的内容,并立即调用
self.callback
。正如OP所指出的,这是精简的代码,我更愿意保留
readerLoad
调用,因为其中可能包含读取代码中的附加功能。非常感谢,工作非常好!!!