file.onload中的Typescript变量未定义

elz*_*zoy 0 variables scope undefined

  filePhotoValue: any = "xexe";

  sendFile(file) {

    var reader = new FileReader();

    reader.onload = function (e:any) {
      console.log(this.filePhotoValue);
    };

  }
Run Code Online (Sandbox Code Playgroud)

为什么要在reader.onload控制台内"undefined"而不是用filePhotoValue xexe?没有编译错误,我想为filePhotoValue insidereader.onload 设置一些值。

Ibr*_*him 6

在onload方法内部时,您将松散方法外部的“ this”的上下文。要解决此问题,您有两种解决方案:将“ this”上下文保存在另一个变量中:

sendFile(file) {

    var reader = new FileReader();

    var self = this;    

    reader.onload = function (e:any) {
      console.log(self.filePhotoValue);
    };

  }
Run Code Online (Sandbox Code Playgroud)

或将当前上下文绑定到该函数:

sendFile(file) {

    var reader = new FileReader();

    reader.onload = function (e:any) {
      console.log(this.filePhotoValue);
    }.bind(this);

  }
Run Code Online (Sandbox Code Playgroud)