TypeScript: Access static methods within classes (the same or another ones)

diosney picture diosney · Sep 1, 2013 · Viewed 87.6k times · Source

Suppose we have the following code:

[Test.js file]:
class Test {
    ...
    public static aStaticFunction():void {
          ...

           this.aMemberFunction(); // <- Issue #1.
    }

    private aMemberFunction():void {
          ...

          this.aStaticFunction(); // <- Issue #2.
    }
}

[Another.js file]:
class Another {
    ...

    private anotherMemberFunction():void {
          Test.aStaticFunction(); // <- Issue #3.
    }
}

See the Issue #x. comments for the issues (3) I want to address.

I've been playing with some configurations by now and I don't get it all yet.

Can you help me to understand how can I access this methods in the three places?

Thanks.

Answer

Fenton picture Fenton · Sep 1, 2013

There is some code below, but there are some important concepts to bear in mind.

A static method does not exist on any instance. There are good reasons for this:

  1. It can be called before you have created a new instance
  2. It can be called from outside an instance, so you wouldn't know which instance the call was related to

So in all cases where you call the static method, you need to use the full name:

Test.aStaticFunction();

If the static method needs to call an instance method, you need to pass that in. This does set off alarm bells for me though. If the static method depends on an instance method, it probably shouldn't be a static method.

To see what I mean, think about this problem.

If I call Test.aStaticFunction() from outside of an instance, when 100 instances have been created, which instance should the static function use? There is no way of telling. If your method needs to know data from the instance or call methods on the instance, it almost certainly shouldn't be static.

So although the code below works, it probably isn't really what you require - what you probably need is to remove the static keyword and make sure you have an instance to call in your other classes.

interface IHasMemberFunction {
    aMemberFunction(): void;
}

class Test {
    public static aStaticFunction(aClass: IHasMemberFunction):void {
           aClass.aMemberFunction();
    }

    private aMemberFunction():void {
          Test.aStaticFunction(this);
    }
}

class Another {
    private anotherMemberFunction():void {
          Test.aStaticFunction(new Test());
    }
}