jdsmith2816
jdsmith2816

Reputation: 325

How to access a static member from within a constructor

class MockFamily implements IFamily {
    static instances: MockFamily[] = [];

    constructor (nodeClass: { new (): Node; }, engine: Engine) {
        MockFamily.instances.push(this);
    }

    /* sniiiiiip */
}

In the above example is there any way to access the static instances value from within the constructor without using the actual class name?

Upvotes: 4

Views: 2200

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89171

Static variables are always accessed trough the class-name. The class object acts as an object with properties. The closest you could come is maybe:

with (MockFamily) {
    instances.push(this);
}

Though I would not recommend it.

Modules are another thing though. At run-time, their contents are variables in a function scope, and can be accessed directly almost anywhere within.

module MyModule {
    var instances: IFamily[] = [];

    export class MockFamily implements IFamily {
        constructor (nodeClass: { new (): Node; }, engine: Engine) {
            instances.push(this);
        }

        /* sniiiiiip */
    }
}

Upvotes: 8

Related Questions