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

标签 typescript this

我正在编写一个 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/

相关文章:

javascript - 从类中删除 onclick 按钮

javascript - 正确封装JS代码,不用担心 "this"

c++ - 为什么没有 'this_class' - 'this' 的静态等价物?

Typescript人机界面学生类(class)关系

javascript - 将 TypeScript 编译为 bundle ..现在怎么办?

javascript - 从类创建派生类型,但省略构造函数( typescript )

git - 我应该将外部库的 TypeScript 定义文件检查到 git 中吗?

angular - 在新标签页中打开新窗口

java - this关键字作为引用变量

javascript - 严格模式默认绑定(bind) "this"关键字