How to refer to the current function in a TypeScript class method body?

Viewed 493

TL;DR: I'm using a named function expression to refer to the current function in ES5; how best to translate to a TypeScript method?


I have the following pattern in a lot of ES5/dojo code:

"use strict";

declare(SuperClass, {

    //...

    someMethod: function fn() {
        //calls the same method in the superclass
        this.inherited(fn, arguments);

        // ...
    }
});

Translating to TypeScript using the @declare decorator from dojo-typings (note: use very carefully; lots of problems exist):

@declare(SuperClass)
class SomeClass {

    //...

    someMethod() {
        this.inherited(
            //Is this the only way to directly reference the method?
            SomeClass.prototype.someMethod,
            arguments
        );

        //...
    }
}

I need to refer to the someMethod within itself in TypeScript.

  • arguments.callee isn't an option, since this is strict-mode code.
  • this.someMethod isn't an option, because I need to refer to the currently executing function. The current someMethod could be overridden in a subclass and called from there using this.inherited()
  • SomeClass.prototype.someMethod would work, but has it really come to that?

The ideal solution would be to simply use the identifier someMethod and for TypeScript to emit a named function expression.

Is there a simple way to refer to the current function without resorting to SomeClass.prototype.method?


EDIT: The limitation here is a consequence of ES6 class syntax, not anything specific to TypeScript. Looks like the only way to refer to a non-overridden class method (without extra legwork) is Class.prototype.method (a great overview is given here: stackoverflow.com/a/43694337/163227).

An idea I came up with: one could define a variable outside the class, then assign the method to the variable after the class declaration:

let someMethod;

class SomeClass {

    //...

    someMethod() {
        this.inherited(someMethod, arguments);

        //...
    }
}

someMethod = SomeClass.prototype.someMethod;
0 Answers
Related