typescript 使用打字稿和“this”对象读取本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34527198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a local file with typescript, and the 'this' object
提问by Noam
I am writing a TypeScript browser application. I need to read the contents of an XML file, and store it in a class. I am having issues with the 'this' object. Here is what I have so far:
我正在编写一个 TypeScript 浏览器应用程序。我需要读取 XML 文件的内容,并将其存储在一个类中。我遇到了“这个”对象的问题。这是我到目前为止所拥有的:
class FileTools {
text: string;
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
reader.onload = file => {
var contents: any = file.target;
this.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
start() {
document.getElementById("file-input").addEventListener("change", this.readSingleFile, false);
}
}
window.onload = () => {
var tcx = new FileTools();
tcx.start();
};
The HTML has a file selection box input type="file" id="file-input"
HTML 有一个文件选择框 input type="file" id="file-input"
The issue is that when the file is loaded, using the 'this' points to the file reader, not to my class. If I add a 'self' variable first like this:
问题是在加载文件时,使用“this”指向文件阅读器,而不是我的班级。如果我像这样先添加一个“自我”变量:
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
var self = this;
reader.onload = file => {
var contents: any = file.target;
self.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
then self points to the input box (as that is the context of the outer method).
然后 self 指向输入框(因为这是外部方法的上下文)。
So the question is, how do I get the real 'this' object for the FileTools reference.
所以问题是,我如何获得 FileTools 引用的真正“this”对象。
Thanks.
谢谢。
采纳答案by toskv
In ES6 and TypeScript even for class methods the regular function rules for this still apply.
在 ES6 和 TypeScript 中,即使对于类方法,常规函数规则仍然适用。
In the startmethod you are sending a reference to the readSingleFilefunction as the callback for the change event.That function will later get called in the input field's context thus changing what thispoints to.
在start方法中,您发送对readSingleFile函数的引用作为更改事件的回调。该函数稍后将在输入字段的上下文中被调用,从而更改this指向的内容。
Try using an arrow function instead to preserve the same context.
尝试使用箭头函数来保留相同的上下文。
start() {
document.getElementById("file-input").addEventListener("change", e => {
this.readSingleFile(e); // this should now be FileTools
}, false);
}