Home > Back-end >  this vs classname for accessing static in typescript
this vs classname for accessing static in typescript

Time:12-15

In typescript, I have noticed that the following approaches are both valid for accessing a static class member.

class MyClass
{
   private static readonly FOO: string = "foo";

   public DoSomething(): void { console.log(MyClass.FOO);}
   public DoSomethingWithThis(): void { console.log(this.FOO); }
}

var instance: MyClass = new MyClass();
instance.DoSomething();
instance.DoSomethingWithThis();

Is there a more correct way? Having come from a C /C# background, by default, I would always use "DoSomething()" over "DoSomethingWithThis()"

CodePudding user response:

This is allowed, accessing static properties from static methods

class MyClass
{
   private static readonly FOO: string = "foo";

   public DoSomething(): void { console.log(MyClass.FOO);}
   public static DoSomethingWithThis(): void { console.log(this.FOO); } // this
}

This is not allowed

var instance: MyClass = new MyClass();
instance.DoSomethingWithThis(); // Property 'DoSomethingWithThis' does not exist on type 'MyClass'.
// Did you mean to access the static member 'MyClass.DoSomethingWithThis' instead?

But you could do this

MyClass.DoSomethingWithThis(); // Static method uses static property.

Is there a more correct way?

The correct way depends of your use case, but as you can see, you can't call this.FOO in DoSomethingWithThis unless it's also declared as static.

  • Related