Robert Balicki
Robert Balicki

Reputation: 1633

Referring to the static class in Typescript

I have the following situation. I want to be able to define a static method on a base class (register) which uses references to other static properties, which should be overridden. For example:

class Base {
    constructor() { }
    public static name = "Override me please";
    public static register = function() { console.log( Base.name ) }
}

class Child extends Base {
    constructor() { super() }
    public static name = "Child";
}

And then I of course would like Child.register() to print out 'Child'. Is it possible to get a reference to the current class? I know I can always pass in a reference to the class, but that seems less elegant than being able to refer to the class directly.

Any help appreciated! Thank you!

Upvotes: 3

Views: 3852

Answers (2)

Brenton Alker
Brenton Alker

Reputation: 9072

Here is an implementation that does what you seem to be after.

class Base {
    constructor() { }
    public static aname = "Override me please";
    public static register = function() { console.log( this.aname ) }
}

class Child extends Base {
    constructor() { super() }
    public static aname = "ChildName";
}

There are 2 things to note.

  1. The way JavaScript this binding works. When you call Child.register(), this will essentially refer to whatever is on the left of the .. In this "static" context, this will refer to the "constructor" function in the generated JavaScript, which is the "Class" in the TypeScript.

  2. Because this refers to a function (in the JavaScript), name is a standard attribute of the function, and your naming of the property probably needs changing (though, this may not be standard, according to the MDN documentation on function.name). The fact that you have the value of the Child.name = "Child" may have masked this.

Upvotes: 2

basarat
basarat

Reputation: 275867

You can use the constructor property which is available on all JavaScript function's prototype and therefore the instances __proto__:

class Base {
    constructor() { }
    public static name = "Override me please";
    public static register = function() { console.log( Base.name ) }
}

class Child extends Base {
    constructor() { 
        super();
        console.log(this.constructor['name']); // use local version
     }
    public static name = "Child";
}

var child = new Child();

Upvotes: 0

Related Questions