Typescript “this” inside a class method

前端 未结 7 1438
温柔的废话
温柔的废话 2020-11-30 02:45

I know this is probably painfully basic, but i am having a tough time wrapping my head around it.

class Main
{
     constructor()
     {
         requestAni         


        
7条回答
  •  猫巷女王i
    2020-11-30 03:15

    The problem arises when you pass a function as a callback. By the time the callback has executed the value of "this" could have changed to the Window, the control invoking the callback, or something else.

    Make sure you always use a lambda expression at the point you pass a reference to the function to be called back. For example

    public addFile(file) {
      this.files.push(file);
    }
    //Not like this
    someObject.doSomething(addFile);
    //but instead, like this
    someObject.doSomething( (file) => addFile(file) );
    

    This compiles to something like

    this.addFile(file) {
      this.files.push(file);
    }
    var _this = this;
    someObject.doSomething(_this.addFile);
    

    Because the addFile function is being called on a specific object reference (_this) it does not use the "this" of the invoker but instead the value of _this.

提交回复
热议问题