Typescript “this” inside a class method

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

    How about doing it this way? Declare a global variable of type "myClass" and initialise it in the constructor of the class:

    var _self: myClass;
    
    class myClass {
        classScopeVar: string = "hello";
    
        constructor() {
            _self = this;
        }
    
        alerter() {
            setTimeout(function () {
                alert(_self.classScopeVar)
            }, 500);
        }
    }
    
    var classInstance = new myClass();
    classInstance.alerter();
    

    Note: It is important NOT to use "self" as it as a special meaning already.

提交回复
热议问题