gpt4 book ai didi

typescript - 使用 typescript 和 'this' 对象读取本地文件

转载 作者:搜寻专家 更新时间:2023-10-30 20:58:09 30 4
gpt4 key购买 nike

我正在编写一个 TypeScript 浏览器应用程序。我需要读取 XML 文件的内容,并将其存储在一个类中。我对“this”对象有疑问。这是我目前所拥有的:

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();
};

HTML有一个文件选择框 输入类型="文件"id="文件输入"

问题是当加载文件时,使用“this”指向文件阅读器,而不是我的类。如果我像这样首先添加一个“self”变量:

  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);
}

然后 self 指向输入框(因为这是外部方法的上下文)。

所以问题是,如何为 FileTools 引用获取真正的“this”对象。

谢谢。

最佳答案

在 ES6 和 TypeScript 中,即使对于类方法,常规函数规则仍然适用。

start 方法中,您发送对 readSingleFile 函数的引用作为更改事件的回调。该函数稍后将在输入字段的上下文中调用,因此更改 this 指向的内容。

尝试使用箭头函数来保留相同的上下文。

 start() {
document.getElementById("file-input").addEventListener("change", e => {
this.readSingleFile(e); // this should now be FileTools
}, false);
}

关于typescript - 使用 typescript 和 'this' 对象读取本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527198/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com