Using self.x for access to class statics instead of classname.x

Topics: Language Specification
Jun 9, 2013 at 10:58 PM
Edited Jun 9, 2013 at 11:20 PM
class SomeTediousLongClassName {

    static count : number;

    public getCount () {
        return SomeTediousLongClassName.count;
        // if would be nice if I could write
        //    return self.count;
    }
}
It looks nicer and if you ever were to rename the class, you wouldn't have to rename all references to statics within the class itself. (PHP uses the self keyword in that way). I realize you can reference static member data within static member functions without a class name prefix, but within non-static member functions you'll have to prefix with the class name.
Jun 10, 2013 at 1:32 PM
If both members are 'static', you can use:
class SomeTediousLongClassName {

    static count : number;

    public static getCount () {
        return count;
    }
}
Jun 10, 2013 at 4:12 PM
Edited Jun 10, 2013 at 5:13 PM
You can, but my issue is that I have to prefix a reference to a static member with the full class name, when that reference is within a non-static method. For the example it's OK to have the getCount() function be static since it doesn't reference any instance data (this.*), but what if it did? E.g.
class SomeTediousLongClassName {

    private static ccount : number = 0;
    private        icount : number = 0;

    public getCounts () {
        return {classCount:    SomeTediousLongClassName.ccount,
                instanceCount: this.icount};
        // if would be nice if I could write it like this instead
        //    return {classCount:self.ccount, instanceCount:this.icount};
    }
}
Jun 10, 2013 at 6:50 PM
Peter,

Since you can reference a class in a variable, you can do this:
class SomeTediousLongClassName {

    private static ccount : number = 0;
    private        icount : number = 0;

    public getCounts () {
        var self = SomeTediousLongClassName;
        return {
                classCount:    self.ccount,
                instanceCount: this.icount
     };
  }
}
Not exactly what you want but useful. I doubt alias to static classes make into TypeScript any time.
Jun 17, 2013 at 2:38 AM
Thanks. This will limit the refactoring work somewhat, if I were to change the class name. Not ideal though. Just for kicks I tried this:
class SomeTediousLongClassName {

    private static ccount : number = 0;
    private        icount : number = 0;
    private static self = SomeTediousLongClassName;

    public getCounts () {
        return {
                classCount:    SomeTediousLongClassName.self.ccount,
                instanceCount: this.icount
     };
  }
}
It gave me an internal compiler error:
/usr/local/lib/node_modules/typescript/bin/tsc.js:24488
                throw err;
                      ^
RangeError: Maximum call stack size exceeded