Typescript “this” inside a class method

前端 未结 7 1439
温柔的废话
温柔的废话 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条回答
  •  天涯浪人
    2020-11-30 03:13

    See page 72 of the typescript language specification https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true

    Arrow Function Expressions

    In the example

    class Messenger {
     message = "Hello World";
     start() {
     setTimeout(() => alert(this.message), 3000);
     }
    };
    var messenger = new Messenger();
    messenger.start();
    

    the use of an arrow function expression causes the callback to have the same this as the surrounding ‘start’ method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding this, for example by copying it into a local variable:

    This is the actual generated Javascript:

    class Messenger {
     message = "Hello World";
     start() {
     var _this = this;
     setTimeout(function() { alert(_this.message); }, 3000);
     }
    };
    

提交回复
热议问题