Typescript “this” inside a class method

前端 未结 7 1440
温柔的废话
温柔的废话 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:14

    If you want this captured the TypeScript way of doing this is via arrow functions. To quote Anders:

    The this in arrow functions is lexically scoped

    Here is the way I like to use this to my advantage:

    class test{
        // Use arrow functions
        func1=(arg:string)=>{
                return arg+" yeah" + this.prop;
        }
        func2=(arg:number)=>{
                return arg+10 + this.prop;
        }       
    
        // some property on this
        prop = 10;      
    }
    

    View this in the TypeScript Playground

    You can see that in the generated JavaScript this is captured outside the function call:

    var _this = this;
    this.prop = 10;
    this.func1 = function (arg) {
        return arg + " yeah" + _this.prop;
    };
    

    so the this value inside the function call (which could be window) would not be used.

    To learn more: “Understanding this in TypeScript” (4:05) – YouTube

提交回复
热议问题