Given:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
export class RTPush extends Mqtt { static mqttClient: MqttClient | null = null; private test = 'haha'; static staticMethod(): MqttClient | null { return this.mqttClient; } testSingleton(): MqttClient | null { return RTPush.mqttClient; } } |
Static methods access Static properties
If you declare a function to be static, it cannot access non-static properties such as test.
1 2 3 |
static strMethod(): string { return this.test; // ERROR: Property 'test' does not exist on type 'typeof RTPush' } |
you must access a property that ALSO is also declared static like so:
1 2 3 4 5 |
static mqttClient: MqttClient | null = null; static staticMethod(): MqttClient | null { return this.mqttClient; } |
This makes it consistent.
Instance Methods access static properties through Class name
But say you are forced to declare the function as an instance method:
1 2 3 |
testSingleton(): MqttClient | null { return RTPush.mqttClient; } |
In that case, you must the access static properties through the className.
You can test to see if both are same:
1 2 |
const racingTouchPushInstance = new RacingTouchPush(); RTPush.staticMethod() === racingTouchPushInstance.testSingleton() ? 'SAME!' : 'NOT SAME' // SAME! |